简体   繁体   English

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:这是我正在谈论的一个例子:

instead of:代替:

var obj = {
    key1: "it",
    key2: function(){return this.key1 + " works!"}
};
alert(obj.key2());

using:使用:

var obj = {
    key1: "it",
    key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());

Both can be problematic.两者都可能有问题。

var obj = {
    key1: "it",
    key2: function(){ return this.key1 + " works!" }
};
var func = obj.key2;
alert(func()); // error

When func is not called as a method of obj , this can reference something else (in here: the global object " window ").func不是作为obj的方法调用时, this可以引用其他东西(在这里:全局对象“ window ”)。

var obj = {
    key1: "it",
    key2: function(){ return obj.key1 + " works!" }
};
var newref = obj;
obj = { key1: "something else"; };
alert(newref.key2()); // "something else works"

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, prevent obj from being exchanged:如果你真的想让它安全,防止obj被交换:

// ES6 - use `const`:
const obj = {
    key1: "it",
    key2: function(){ return obj.key1 + " works always!" }
};

// ES5: use a closure where the `obj` is stored in a local-scoped variable:
var obj = (function(){
    var local = {
        key1: "it",
        key2: function(){ return local.key1 + " works always!" }
    };
    return local;
})();

or you bind() the function to the object:或者您bind()函数bind()到对象:

var obj = {
    key1: "it",
    key2: function(){ return this.key1 + " works always!" }
}
obj.key2 = obj.key2.bind(obj);

There will be a difference in variable scope binding.变量作用域绑定会有所不同。 If you modify obj later, you will modify the return value of key2:如果后面修改obj,会修改key2的返回值:

var newobj = obj;
obj = { key1: "new" };
alert(newobj.key2());

Now it alerts "new works!", because even though you are calling key2() on the original object (which is now newobj ), the reference to obj.key1 now binds to the value of the new obj instance.现在它会提醒“新作品!”,因为即使您在原始对象(现在是newobj )上调用key2() ),对obj.key1的引用现在绑定到新obj实例的值。 Using this prevents this from happening.使用this可以防止这种情况发生。

Demo: http://jsfiddle.net/m6CU3/演示: http : //jsfiddle.net/m6CU3/

If you are not using prototype object, you czn go like that.如果你不使用原型对象,你就那样做。 as all instances of your object will return the value of the obj instance...因为对象的所有实例都将返回 obj 实例的值...

Either or both of those techniques may apply depending on the situation.根据情况,可以应用这些技术中的一种或两种。

The value of this within a function depends on how the function was called.函数中this的值取决于函数的调用方式。 If you call a function as property of an object like this:如果你像这样调用一个函数作为对象的属性:

obj.key2();
//or
obj["key2"]();

Then this will be that object.那么this将是那个对象。 Whether the object was created via an object literal or some other means is not relevant.对象是通过对象文字还是其他方式创建的并不相关。

But you can use .call() or .apply() to call a function and explicitly set this to some other object.但是你可以使用.call().apply()调用一个函数,并明确设置this为其他对象。

Consider also:还要考虑:

var obj = {
    key1: "it",
    key2: function(){return this.key1 + " works!"}
};
alert(obj.key2()); // alerts "it works!"

var func = obj.key2;
alert(func())​;     // alerts "undefined works!"

I'm setting up func to reference the same function as obj.key2 , but calling it as func() does not set this to obj .我设立func引用相同的功能obj.key2 ,但称这是为func()设置thisobj

For more information have a look at what MDN has to say about this .欲了解更多信息,看看有什么MDN不得不说的this

I don't think there are any implications off the top of my head.我不认为我的头顶有任何影响。 Just make sure you don't accidentally do this at any point:只要确保您在任何时候都不会不小心这样做:

var obj = {
    key1: "it",
    key2: key1 + " works!"
}

As that will cause an error.因为这会导致错误。 Other than that, you should be good to go!除此之外,你应该很高兴去!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM