即使在阅读了网站和SO上的教程之后,我也无法理解call/apply如何工作。我了解基本的机制,直到事情变得嵌套。如果不依赖that = this,我该如何使用call函数来代替闭包呢?
var createPerson = function () {
var that = this;
var name;
return {
bio: {
name: function (name) {
that.name = name;
}
},
getInfo: {
getName: function () {
return that.name;
}
}
}
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());
你所要做的就是在你的函数上使用this
,并在返回的对象上使用call
。
var createPerson = function () {
return {
bio: {
name: function (name) {
this.name = name;
}
},
getInfo: {
getName: function () {
return this.name;
}
}
}
}
var john = createPerson();
john.bio.name.call(john, 'Jonathan');
console.log(person.getInfo.getName.call(john));
Function.prototype.call
将调用您的函数,john
为this
。
Function.prototype.bind
示例:
var createPerson = function () {
var person = {
bio: {},
getInfo: {}
};
person.bio.name = Function.bind.call(function (name) {
this.name = name;
}, person);
person.getInfo.getName = Function.bind.call(function () {
return this.name;
}, person);
return person;
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());
请注意,您可以很容易地将它替换为:
var createPerson = function () {
var person = {
bio: {},
getInfo: {}
};
person.bio.name = function (name) {
person.name = name;
}
person.getInfo.getName = function () {
return person.name;
}
return person;
}
var john = createPerson();
john.bio.name("Johnathan");
console.log(john.getInfo.getName());