如果我有以下代码:
var obj = {
x: 34,
init: function() {
alert(this.x);
alert(obj.x)
}
};
两个警报都显示34.但有什么不同,哪一个比另一个更好?
我在jsperf中做了一个测试,看起来this
有点快,但我仍然不了解这两个版本的内部工作原理。
http://jsperf.com/name-vs-this-in-obj
答案 0 :(得分:4)
除了前面答案中提到的阴影等之外,使用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
我在这里做的是,我创建的object
名字叫John Doe'然后我创建继承自它的anotherObject
。现在,在这种情况下,您希望anotherObject.print()
打印自己的名称。但它没有。
这是因为您的函数与该特定对象相关联。如果我改为使用this
,它会恰当地引用新对象。
另外,想象一下如果我这样做会发生什么。
delete object.name;
anotherObject.print() // Error!
这是因为即使你认为它与前一个对象无关,它的功能仍然是指那个属性。不是吗?
因此,请保持通用。使用this
。我说保持你的代码更干燥。
答案 1 :(得分:2)
this
不一定与obj
相同。这取决于函数的调用方式。
obj.init()
进行调用,obj
将与this
相同。setTimeout(obj.init, 500)
,this
将是浏览器中的全局对象(window
,除非您使用严格模式)< / LI>
答案 2 :(得分:1)
我想说这里有两个不同之处:
this
可能会被遮蔽。不幸的是,在JavaScript中创建一个匿名函数会将this
替换为您所在的新匿名函数,而不是您想要访问的当前对象。this
会更灵活。 this
可能更快,因为JavaScript不需要查找引用。