Javascript:在自己的键的函数中使用对象字面量引用而不是“this" [英] Javascript: Object Literal reference in own key's function instead of 'this'

查看:26
本文介绍了Javascript:在自己的键的函数中使用对象字面量引用而不是“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 的方法被调用时,this 可以引用别的东西(在这里:全局对象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"

在这里,我们从另一个引用访问对象,尽管函数中的 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, prevent obj from being exchanged:

// 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;
})();

或者你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屋!

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