var Animal = {
newInstance: function(type) {
return {
type: type,
template: (function(type) {
return $('.item[type="' + type + '"]', "#template").clone(false);
})(this.type)
};
}
};
如上。this每次都是引用Window,请问怎么样解决?
var Animal = {
newInstance: function(type) {
return {
type: type,
template: function() {
return $('.item[type="' + this.type + '"]', "#template").clone(false);
}
};
}
};
或者
var Animal = {
newInstance: function(type) {
return {
type: type,
template: (function(type) {
return $('.item[type="' + type + '"]', "#template").clone(false);
})(type)
};
}
};
this引用的不是window对象,是Animal对象啊。
由于Animal对象没有定义type属性,所以才会发生错误
这里为什么要用this?,如果你要使用newInstance传进来的值,直接type就好,无需加this。
以下是自执行的表达式:
var i = '值';
(function(ii){
#使用ii(这里ii的值即闭包传参进来的i值)
})(i)