【问题标题】:Javascript literal object, reference to itselfJavascript 文字对象,对自身的引用
【发布时间】:2011-12-01 20:23:41
【问题描述】:

我有这个示例代码:

var foo = {

    self: this,

    init: function(){

        self.doStuff();
    },

    doStuff: function(){
        alert('doing stuff');   
    }

}

foo.init();

为什么引用“self”不起作用?

谢谢!

【问题讨论】:

标签: javascript object self-reference


【解决方案1】:

因为在您声明对象字面量 this 时,它不是对对象的引用,而是对调用上下文的任何引用。

【讨论】:

  • 谢谢,这就解释了!
【解决方案2】:

this 的值取决于当前函数的调用方式。它不引用当前对象。

这将起作用:

var foo = {
    init: function(){
        this.doStuff();
    },
    doStuff: function(){
        alert('doing stuff');   
    }
};

foo.init();

因为当你调用foo.init()this变成foo

【讨论】:

  • 谢谢!我有一个问题,因为如果我在对象函数中写这个,像这样..: init: function(){ $('#element').click(function(){ this.doStuff(); //"this " 是对 jQuery 对象的引用 }) } 但是..为什么这段代码不起作用?初始化:函数(){自我=这个; $('#element').click(function(){ self.doStuff(); //"this" 是 jQuery 对象的引用 }) }
  • self 是一个全局变量,您可能会在其他地方覆盖它。
【解决方案3】:

跟进 Qeuntin 的回复,您将使用以下内容来实现您正在寻找的内容

var foo = {

    self: false,

    init: function(){
        self = this
        self.doStuff();
    },

    doStuff: function(){
        alert('doing stuff');   
    },
}

编辑:因为有人指出,虽然这解决了 OP 的问题(即它有效),但这并不是你应该如何去做的。所以,这里有一个范围参考。

function A()
{
    //Semi-private / hidden var
    var pVar = "I'm a private, err hidden, variable",
        //fn (technically a var)
        pFn = function(){},
        //empty var, placholder for hidden fn
        privatePlaceholderFn;

    //Instance-time... public fn
   this.instancePublicFn = function()
    {
        console.log("--- instace public ---");
        //Print hidden var to cosole
        console.log(pVar);
        //Call hidden fn
        instancePrivateFn();
        console.log("--->Setting  private from instance public")
        //Set the hidden fn
        setPrivate();
        console.log("--- / instance public ---");
    }
    //Pass fn to private method.
    this.setPrivFromOutside = function(fn)
    {
        setPrivateFromPrivateYetOutside(fn);
    }

    //Set the hidden fn
    this.iPFnPlaceholderSetter = function(fn)
    {
        privatePlaceholderFn = fn;
    }

    //Call the semi-private / hidden fn
    this.callPrivate = function()
    {
       privatePlaceholderFn();
    }
    //A misnomer, proves the scope exists. See "function setPrivate()"
    this.setPrivateFromInstance = function()
    {
        //Prove scope exists
        console.log(privatePlaceholderFn);
        console.log("Private From instance - gets inside scope");

    }
    //Set hidden fn from private method
    function setPrivate()
    {
        privatePlaceholderFn = function()
        {
            //Show scope exists
            console.log(pVar);
        }
    }
    //Set the hidden fn from hidden method
    function setPrivateFromPrivateYetOutside(fn)
    {
        //fn's scope won't resolve to inside
        privatePlaceholderFn = fn;
    }
    //Private / hidden messager
    function instancePrivateFn()
    {
        //Just loggin' something
        console.log("Instance Private method");
    }
}
//Add an object method to the prototype
A.prototype.protoPuFn = function(){
    console.log("---> Private var from object literal method");
    //console.log(pVar)
}

//...
a = new A();

//Add object literal fn
a.objFn = function()
{
    console.log("Object literal defined public fn - Gets outside scope");
    //console.log(pVar);
}
//Set private / hidden placeholder fn
a.iPFnPlaceholderSetter(function()
{
    console.log("Hidden fn, passed through instance public - gets outside scope");
    //console.log(pVar);
});
//Attempt to read hidden var
console.log(a.pVar);
//Call object literal defined fn
a.objFn();
//Call the hidden fn
a.callPrivate();
//Call prototype added fn
a.protoPuFn();
//Call instance added public fn
a.instancePublicFn();
//Call private / hidden method (set
a.callPrivate();
//Same as iPFnPlaceholderSetter except the param is passed to a hidden method, before seting.
a.setPrivFromOutside(function()
{
    console.log("-->Passed from outside, through public then private setters");
    //console.log(pVar)
})
//Call the hidden method
a.callPrivate();
//Set hidden fn from instance public
a.setPrivateFromInstance();
//Call the hidden method.
a.callPrivate();
//Use evi(a)l fn to steal scope.
a.evil("this.meth = function(){console.log(pVar)}");
//Call fn with stolen scope
a.meth();

【讨论】:

  • 这个答案不正确。它仍然指的是全局(或相对全局)变量“self”,而不是对象的“self”属性。
  • 原谅我的无知,但是第二个例子不能写成对象字面量形式吗?
【解决方案4】:

ES6 为对象属性提供了 getter,因此您可以使用它们来引用对象本身并使用它的其他成员:

var foo = {
     prop1: 1,

     get prop2() { return this.prop1 + 1; }
}

// foo.prop2 = 2;

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    相关资源
    最近更新 更多