Javascript:在自己的键的函数中的对象文字引用而不是'this' [英] Javascript: Object Literal reference in own key's function instead of 'this'
问题描述
在一个函数中引用一个对象文字是否有问题,该函数是该文字的一部分?它似乎工作得很好,但我想确保没有其他含义。
Is it problematic to reference an object literal within a function which is part of that very literal? It seems to work just fine, but I want to make sure there aren't other implications.
以下是我所说的一个例子:
Here's an example of what I'm talking about:
而不是:
var obj = {
key1: "it",
key2: function(){return this.key1 + " works!"}
};
alert(obj.key2());
使用:
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
推荐答案
两者都有问题。
var obj = {
key1: "it",
key2: function(){ return this.key1 + " works!" }
};
var func = obj.key2;
alert(func()); // error
未调用 func
时作为 obj
的方法, 此
可以引用其他内容(在此处:全局对象 window
)。
When func
is not called as a method of obj
, this
can reference something else (in here: the global object "window
").
var obj = {
key1: "it",
key2: function(){ return obj.key1 + " works!" }
};
var newref = obj;
obj = { key1: "something else"; };
alert(newref.key2()); // "something else works"
在这里我们从另一个引用访问该对象,尽管<$函数中的c $ c> obj 现在可能指向其他一些对象。
In here we access the object from another reference, though the obj
in the function may now point to some other object.
所以你必须选择哪种情况更有可能。如果你真的想让它变得安全,你可以使用一个封闭,其中 obj
的作用域是无法改变的:
So you will have to choose which case is more likely. If you really want to make it safe, you can use a closure where obj
is scoped and can't be changed:
var obj = (function(){
var local = {
key1: "it",
key2: function(){ return local.key1 + " works always!" }
};
return local;
})();
或者 bind()
对象的函数:
or you bind()
the function to the object:
var obj = {
key1: "it",
key2: function(){ return this.key1 + " works always!" }
}
obj.key2 = obj.key2.bind(obj);
这篇关于Javascript:在自己的键的函数中的对象文字引用而不是'this'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!