簡體   English   中英

如何訪問自身內的對象,另一個對象內的對象?

[英]How do I access an object within itself, within another object?

我知道在對象中使用“ this”關鍵字會引用該對象,但是嵌套對象呢?

 var mainObj = { childObj: { addProperty: function() { this.message = "HELLO"; } } }; mainObj.childObj.addProperty(); 

從這里,如何在“ childObj”對象的內部和外部訪問“ this.message”屬性?

快速答案:在mainObj的不同方法中,可以使用this.childObj.message ,也可以從外部使用mainObj.childObj.message

 var mainObj = { childObj: { addProperty: function() { this.message = "HELLO"; } }, msg() { return this.childObj.message; }, }; mainObj.childObj.addProperty(); console.log(mainObj.msg()); // HELLO console.log(mainObj.childObj.message); // HELLO 

關於this一些上下文

從MDN文檔中

與其他語言相比,函數的this關鍵字在JavaScript中的行為略有不同。 在嚴格模式和非嚴格模式之間也有一些區別。

在大多數情況下,其值取決於函數的調用方式。 在執行過程中不能通過賦值來設置它,並且每次調用該函數時可能會有所不同。 ES5引入了bind方法來設置函數this的值,而不管其調用方式如何,ES2015引入了arrow函數,該函數不提供自己的this綁定(它保留了封閉詞法上下文的this值)。

基本上,根據上下文, this可能意味着不同的事情:

全球背景

在任何函數之外, this是指全局對象。 在瀏覽器中,這意味着this === window

功能上下文

在功能,價值this 取決於你如何調用函數,以及是否使用的是strict模式或沒有。 ,基本上它可以指向全局對象或繼承執行上下文。

當調用函數作為對象的方法時,它將被設置為調用中擁有該方法的對象:

 //'use strict'; window.message = 'wat'; const obj1 = { message: 'hi 1', hi() { return this.message; }}; const obj2 = { message: 'hi 2', hi() { return this.message; }}; // Normal invocation console.log(obj1.hi()) console.log(obj2.hi()) // As functions: const obj1Hi = obj1.hi; console.log(obj1Hi()); // returns wat on non-strict mode! // enable use strict to see the error thrown by this defaulting to undefined/ // Swap the functions around obj1.hi = obj2.hi; obj2.hi = obj1Hi; console.log(obj1.hi()) // still uses message from obj1 console.log(obj2.hi()) // still uses message from obj2 // You can even do some `bind` magic to force the context on a function: console.log(obj1Hi.bind(obj1)()); // hi 1 console.log(obj1Hi.bind(obj2)()); // hi 2 

暫無
暫無

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

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