使用'this'以及在对象内部引用的对象名称

Whats the difference between using 'this' and the object name for reference inside the object?

本文关键字:对象 引用 内部 this 使用      更新时间:2023-09-26

如果我有以下代码:

var obj = {
    x: 34,
    init: function() {
        alert(this.x);
        alert(obj.x)
    }
};

两个警报都显示34。但是两者有什么区别,一个比另一个好吗?

http://jsfiddle.net/4scz435q/

我在jsperf中做了一个测试,看起来this更快一些,但我仍然不明白两个版本的内部工作原理。http://jsperf.com/name-vs-this-in-obj

除了前面的答案中提到的阴影等,使用this更通用,因此在某些场景中会更有效地工作。让我举例说明。

var object = {
    name: 'John Doe',
    print: function () {
        console.log(object.name);
    }
};
var anotherObject = Object.create(object);
object.print(); // John Doe
anotherObject.print(); // John Doe
anotherObject.name = 'Jane Doe';
console.log(anotherObject.name); // Jane Doe
anotherObject.print(); // John Doe

我在这里所做的是,我创建了一个名称为"John Doe"的object,然后我创建了从它继承的anotherObject。现在在这个场景中,您希望anotherObject.print()打印自己的名称。但它没有。

这是因为您的函数绑定到特定对象。如果我使用this,它就会正确地引用新对象。

同样,想象一下如果我这样做会发生什么。

delete object.name;
anotherObject.print() // Error!
http://jsfiddle.net/uxy08zxz/

这是因为即使你认为它与前一个对象无关,它的函数仍然指向那个属性。不是吗?

因此,保持它的泛型。使用this

函数内的this不一定与obj相同。这取决于如何调用函数。

  • 如果使用obj.init()调用,obj将与this相同。
  • 如果使用事件处理程序调用,或setTimeout setTimeout(obj.init, 500), this将是全局对象(window在浏览器中,除非你使用严格模式)

很好的MDN参考

我想说这里有两个不同:

  1. this可以被阴影。不幸的是,在JavaScript中创建匿名函数可能会将this替换为对新匿名函数的引用,而不是您想要访问的当前对象。
  2. 当你不担心阴影,this是更灵活的,如果对象的名称改变。

this在这种情况下可能更快,因为JavaScript不需要查找引用