Javascript literal object, reference to itself

前端 未结 4 1193
灰色年华
灰色年华 2020-12-16 23:44

I have this example code:

var foo = {

    self: this,

    init: function(){

        self.doStuff();
    },

    doStuff: function(){
        alert(\'doing         


        
4条回答
  •  囚心锁ツ
    2020-12-17 00:31

    The value of this is determined by how the current function was called. It does not refer to the current object.

    This will work:

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

    Since when you call foo.init(), this becomes foo.

提交回复
热议问题