示例代码:
var people={
name:["张三","李四","王五","赵六"],
getName:function(){
return function(){
return {
n:this.name[3],
m:this
}
}
}
}
var pname = people.getName();
console.log("名字:" + pname().n);
console.log( pname().m);
输出:
名字:undefined
global
原因:this.name[i]中的this的指向不是people里面的this
js做法:
var people = {
name: ["张三", "李四", "王五", "赵六"],
getname: function () {
var nameMid = this.name;
return function () {
return {
n: nameMid[3]
};
};
}
};
var myName = people.getname();
console.log("名字:" + myName().n);
输出:
名字:赵六
Lambads做法:Lambads表达式 ()=>{ }
var people = {
name: ["张三", "李四", "王五", "赵六"],
getName: function () {
return () => {
return {
n: this.name[3]
}
}
}
}
var pname = people.getName();
console.log("名字:" + pname().n);
输出:
名字:赵六