2016-01-03 316 views
-1
var john = { 

    peter: {}, 

    one: function() { alert('one'); }, 

    two: function() { 
     peter.handler = function() { 
      one(); // JS cannot find one(). one() undefined. 

      Console.log(this); // object peter 
     } 

     Console.log(this); // object john 
    } 
} 

如何在peter.handler內使用one()如何調用在對象範圍中聲明的javascript函數?

回答

1

您可以使用this來訪問函數調用的上下文,該函數調用通常是指定函數的對象,但在代碼中的某處(通常爲HERE.method_name())明確指定。

沒有辦法(對所有變量和測試進行循環)以瞭解其他對象具有哪些其他對象的屬性值。

識別john(這是用於獲取one的先決條件)的唯一方法是從twohandler功能內明確地引用它。

0

嘗試使用Object john本身調用javascript函數。

例如: -

john.one();

0

你總是可以做這樣的事情,並使用呼叫john.one()

var john = { 

    peter: {}, 

    one: function() { alert('one'); }, 

    two: function() { 
     peter.handler = function() { 
      john.one(); // JS cannot find one(). one() undefined. 

      Console.log(this); // object peter 
     } 

     Console.log(this); // object john 
    } 
} 
0

訪問的父對象,你應該使用This關鍵字

查看updated cod下文E:

var john = { 

    peter: {}, 

    one: function() { alert('one'); }, 

    two: function() { 
     this.peter.handler = function() { 
      one(); // JS cannot find one(). one() undefined. 

      console.log(this); // parent object: peter 
     }; 

     console.log(this); // object john 
     this.one(); 
    } 
}; 

john.two(); 
+0

但是'one'內'this.peter.handler'仍然是不確定的。你真的嘗試過嗎? –

0

您可以使用如下

var john = { 

    peter: {}, 

    one: function() { alert('one'); }, 

    two: function() { 
     this.peter.handler = function() { 
      john.one(); // JS cannot find one(). one() undefined. 

      console.log(this); // object peter 
     } 

     console.log(this.peter.handler()); // call peter handler 
    } 
}