繁体   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