在对象内部使用'this'和对象名称之间的区别是什么? [英] Whats the difference between using 'this' and the object name for reference inside the object?

查看:117
本文介绍了在对象内部使用'this'和对象名称之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

var obj = {

    x: 34,

    init: function() {
        alert(this.x);
        alert(obj.x)
    }

};

两个警报都显示34.但有什么不同,哪一个比另一个好?

Both alerts displays 34. But what is the difference, and is one better than the other?

http://jsfiddle.net/4scz435q/

我在jsperf做了一个测试,似乎这个有点快,但我还是不明白两个版本的内部工作原理。
http://jsperf.com/name-vs-this-in-obj

I made a test in jsperf, and it seems this is a bit faster, but I still don't understand the inner workings of the two versions. http://jsperf.com/name-vs-this-in-obj

推荐答案

除了前面答案中提到的阴影等,使用这个更通用,因此在某些情况下可以更有效地工作。让我来说明一下。

Besides the shadowing and so on mentioned in the previous answers, using this is more generic and thus will work more effectively in certain scenarios. Let me illustrate.

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,然后我创建继承自它的 anotherObject 。现在,在这种情况下,您希望 anotherObject.print()打印自己的名称。但事实并非如此。

What I'm doing here is that I'm creating an object that has a name 'John Doe' and then I create anotherObject that inherits from it. Now in this scenario, you would expect anotherObject.print() to print its own name. But it doesn't.

这是因为您的函数与该特定对象相关联。如果我本来会使用这个,它会适当地引用新对象。

This is because your function is tied to that particular object. If I would have used this instead, it would have referred to the new object appropriately.

另外,想象一下如果我这样做会发生。

Also, imagine what happens if I were to do this.

delete object.name;
anotherObject.print() // Error!

http://jsfiddle.net/uxy08zxz/

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

This is because even though you think it has nothing to do with that previous object, its function still refers to that very property. Doesn't it?

因此,请保持通用。使用。我说保持你的代码更干燥。

Hence, keep it generic. Use this. Keeps your code drier, I say.

这篇关于在对象内部使用'this'和对象名称之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆