zoukankan      html  css  js  c++  java
  • 浅谈JavaScript--this指向

    js中this的值取决于调用的模式

    • 方法调用模式
    var student={
        name:"adoctors",
        showThis:function(){
            console.log(this);          //此处this为整个student对象,包括其中的属性和方法
            console.log(this.name);   // 'adoctors'
        }
    }
    
    • 函数调用模式
    function fn(){
        console.log(this);   //this指向window对象
        
        var name = "adoctors";
        console.log(this.name);   //undefined
        
        //也可通过赋值变量改变this指向
        var that=this;
        ···
    }
    
    • 构造器调用模式
    var fn = function (status){
        this.status = status;
    }
    fn.prototype.get_status = function(){
        return this.status;
    }
    var test = new fn('my status');
    console.log(test.get_status);   //my status,this指向test
     
    
    • apply和call调用模式
    function foo(){
        console.log(this.fruit);
    }
    // 定义一个全局变量,等同于window.fruit = "banana";
    var fruit = "banana";
    
    var  o = {
        fruit : "apple"
    };
        
    foo.apply(window);  // "banana";
    foo.call(o);  // "apple";
    
    

    apply和call的唯一区别,就是在传参的时候,apply的参数需要放在一个数组里面,而call不需要;

  • 相关阅读:
    优化-IO
    优化-cpu
    优化-内存
    系统优化
    snort -- 入侵检测系统
    tripwire--入侵检测系统
    sudo
    selinux
    pptpd
    C++ 内联函数
  • 原文地址:https://www.cnblogs.com/adoctors/p/8505864.html
Copyright © 2011-2022 走看看