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