我目前正在学习 javascript 并试图理解“this”。在下面的代码中,为什么我无法在渲染方法中访问 this.ul ? (它说它是未定义的)。我被引导相信 cacheDOM 方法会将 this.ul 绑定(bind)到 people 对象,然后该对象可以被该对象的其余部分访问。
(function(){
var people = {
people: ['Tom', 'Sean'],
init: function() {
this.cacheDOM();
this.render();
},
cacheDOM: function() {
this.input = window.document.querySelector('.input');
this.button = window.document.querySelector('.button');
this.ul = window.document.querySelector('.ul');
},
render: function() {
var data = this.people;
data.map(function(person){
var li = document.createElement('li');
li.textContent = person;
this.ul.appendChild(li);
});
}
};
people.init();
})();
已修复。将 var ul = this.ul
添加到渲染函数的顶部,然后允许 map 函数正确访问!
最佳答案
这个参数的值由调用模式决定。
JavaScript 中有四种调用模式: 方法调用模式、函数调用模式、构造函数调用 模式和 apply 调用模式。 检查this link理解这些模式。
检查以下render函数的实现;
render: function() {
var data = this.people;
var that = this;
data.map(function(person){
var li = document.createElement('li');
li.textContent = person;
that.ul.appendChild(li);
});
}
或者您可以将 this 的值作为参数传递给 map() 函数:
render: function() {
var data = this.people;
data.map(function(person){
var li = document.createElement('li');
li.textContent = person;
this.ul.appendChild(li);
},this);
}
关于javascript - 对象字面量方法的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34792950/