簡體   English   中英

創建js對象時,為什么不能在另一個已定義函數中使用已定義函數?

[英]Why can't I use a defined function inside another defined function,when creating an js object?

代碼像這樣

var ob = {
    a: function() {
        b()
    },
    b: function() {
        console.log("hi")
    }
};

如您所見,您做不到

ob.a() //returns error

有人可以深入解釋原因嗎?

因為b在當前作用域中不存在(在這種情況下為全局范圍)。

但是,這可行:

var ob = {
  a: function () {
    this.b()
  },
  b: function () {
    console.log('hi')
  }
};

因為this是指ob對象。

b是稱為ob的對象的屬性。 話雖如此,如果您使用

ob.b

而不是b您將解決您的問題。

var ob = {
    a:function(){ 
        ob.b() 
    },
    b:function(){
        console.log("hi")
    }
};

實現此目的的另一種方法是使用this運算符。

var ob = {
    a:function(){ 
        this.b() 
    },
    b:function(){
        console.log("hi")
    }
};

this包含對您定義的對象的引用。 因此,使用它可以訪問is屬性。 這是第一種更好的方法,因為如果您稍后決定將ob的名稱更改為obj ,則不會在兩個地方進行更改。

在任何地方都沒有定義函數b ,它是對象ob的屬性,因此您可以在a內部a其稱為this.b

var ob = {
    a: function () {
        this.b();
    },
    b: function () {
        console.log("hi");
    }
};

ob.a();

您也可以作為ob.b()訪問b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM