[英]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.