码迷,mamicode.com
首页 > Web开发 > 详细

js中关于this的理解

时间:2016-07-28 16:27:01      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

常见:在普通函数中的this,指向 全局

function thisObj(name){
    this.name = name;
    console.log(this);
}

但是在严格模式下的函数,this指向 underfined.

混淆点.内部函数中的this指向:

var numbers = {
   numberA: 5,
   numberB: 10,
   sum: function() {
     console.log(this === numbers); // => true
     function calculate() {
       // this is window or undefined in strict mode
       console.log(this === window); // => true
       console.log(this === numbers); // => false;
       return this.numberA + this.numberB;
     };
     return calculate();
   }
};
numbers.sum();

在上述numbers对象中,sum函数是numbers对象的方法。所以sum函数中的this指向numbers对象。

但是在内部函数calculate中,我们如果以为this也是指向numbers对象那就打错特错了。

在这里该内部对象是一个函数调用,并不是对象的方法。所以calculate中的this指向 window。

所以为了避免calculate中的this指向错误。要进行如下修改,将this值指向numbers对象。

var numbers = {
   numberA: 5,
   numberB: 10,
   sum: function() {
     console.log(this === numbers); // => true
     function calculate() {
       // this is window or undefined in strict mode
       console.log(this === window); // => true
       console.log(this === numbers); // => false;
       return this.numberA + this.numberB;
     };
     return calculate.call(this);//return calculate();
   }
};
numbers.sum();

混淆点.从Object中分离的方法

function People(name){
    this.name = name;
    this.action = function(){
        console.log("this是否等于window " + this === window)
        console.log(this.name);//注意是这里的this 指向的应该是 window
    }
}
var xiaoA = new People(‘xyf‘);
var zz = xiaoA.action;
zz();  //输出错误
xiaoA.action() // 输出 xyf
setInterval(xiaoA.action,500000);//错误
setInterval(xiaoA.action.bind(xiaoA),500000);//循环输出 xyf

这里要注意  如果直接输出 xiaoA.action();是可以正确输出的。但是当我们将xiaoA.action赋值给变量zz之后。该action方法就从原来的Object中分离了。这时候的this指向全局变量。setInterval定时器也会产生这样的问题。如果要正确显示需要用bind重新绑定对象。

var zz =xiaoA.action.bind(xiaoA);
zz(); //输出 xyf

 

js中关于this的理解

标签:

原文地址:http://www.cnblogs.com/enmeen/p/5714892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!