简体   繁体   English

从子级访问 JavaScript 对象中的根属性

[英]Accessing root properties in JavaScript objects from children

I have a block of JavaScript in which notably, this.id resolves to undefined .我有一个 JavaScript 块,其中this.id解析为undefined

The console indicates that this resolves to the methods object.控制台指示this解析为methods对象。 I originally thought it would resolve to item .我原本以为它会解析为item My question is, in my buy method, how do I access the id property.我的问题是,在我的buy方法中,如何访问id属性。 Please note, I do NOT want to move buy out of the methods object.请注意,我不想将buy移出methods对象。 I'm working to understand this.我正在努力理解这一点。

 const item = { id: 5, methods: { buy() { alert('buying item ' + this.id); console.log(this); } } }; const myButton = document.getElementById('myButton'); myButton.addEventListener('click', () => { item.methods.buy(); });
 <button id="myButton"> Buy </button>

You can use Function.prototype.call() as item.methods.buy.call(item);您可以使用Function.prototype.call()作为item.methods.buy.call(item); to bind item to this .item绑定到this

Try it below.下面试试看。

 const item = { id: 5, methods: { buy() { alert('buying item ' + this.id); console.log(this); } } }; const myButton = document.getElementById('myButton'); myButton.addEventListener('click', () => { item.methods.buy.call(item); });
 <button id="myButton"> Buy </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM