我想知道为什么要将此对象绑定到返回对象才能使此方法起作用。
function person( _name ) {
function InnerPerson( _name ) {
this.name = _name;
}
InnerPerson.prototype = {
me: function() {
return "Hi, my name is " + this.name;
}
};
var innerPerson = new InnerPerson( _name );
return {
me: innerPerson.me // this only works if you add .bind( innerPerson )
};
}
var josh= person("josh");
console.log( josh.me() ); // Hi, my name is undefined
此执行中的逐步操作是什么?如果已明确创建对象并且this.name
对象的返回值在josh.me()
中有引用,则在调用person
时如何定义me: innerPerson.me
?为什么在此示例中需要bind
?
对此进行解释的部分原因,不仅是this
或上下文在Javascript中的工作方式。在这个问题上,有一些特定的事情正在发生,那就是从一般意义上理解this
并不能完全解释问题。例如,如果我调用innerPerson.me()
而不返回函数定义,则将获得正确的上下文。正是由于我要返回的内容,上下文和this
才发生变化。
答案 0 :(得分:0)
您必须了解this的工作方式。您可以通过将一个thisParent
放在InnerPerson
及其prototype
中使用它来实现。
function person(_name) {
var thisParent = this;
function InnerPerson(_name) {
thisParent.name = _name;
}
InnerPerson.prototype = {
me: function() {
return "Hi, my name is " + thisParent.name;
}
};
var innerPerson = new InnerPerson(_name);
return {
me: innerPerson.me // this only works if you add .bind( innerPerson )
};
}
var josh = person("josh");
console.log(josh.me());