[英]Why I can't access a JavaScript function defined in a .js file from another .js file?
[英]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.