let info = {
name: "Mark",
age: 23,
location: function(cname) {
console.log("Hello " + this.name + " you are " + this.age + " years old and you live in " + cname)
}
};
let details = info.location.bind(info, "mumbai");
console.log(details);
代码有什么问题? 我在这里使用了绑定方法,我之前确实验证了语法。
你想做什么?下面的代码会在控制台中给你"你好马克,你23岁了,你住在孟买",我相信你正在尝试。
let info = {
name : "Mark",
age : 23 ,
location : function city(cname){
console.log("Hello "+this.name+ " you are "+ this.age+ " years old and you live in " + cname )
}
};
info.location("mumbai")
如果调用位置作为对象信息的方法,则其"this"将自动设置为对象信息。所以你不需要绑定。如果您像下面这样调用它,则需要绑定:
const myFun = info.location;
myFun = myFun.bind(info);
myFun("mumbai");
你不需要绑定,如果你在你的对象上调用函数,它将显示所需的结果,但是如果你在全局上下文中调用它,那么this.props将是未定义的。
这完全取决于您如何调用函数,自定义对象范围或全局窗口对象范围,具体取决于此,此引用将延迟。
let info = {
name: "Mark",
age: 23,
location: function(cname) {
console.log("Hello " + this.name + " you are " + this.age + " years old and you live in " + cname)
}
};
// displays undefined this refers to window object
const globalFunc = info.location
globalFunc('mumbai')
// calling funciton on global scope with passing info object as an argument
globalFunc.call(info,'mumbai')
info.location('mumbai')