gpt4 book ai didi

javaScript .bind() 不会返回一个新函数,该函数在调用时将具有等于我传递的 arg 的 'this'

转载 作者:行者123 更新时间:2023-12-02 23:40:34 24 4
gpt4 key购买 nike

我有以下代码。

var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}

var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}


var logname = function() {
console.log(this.getName());
}.bind(person1); // not working as expected when .bind() here !!!


var newlogname1 = logname.bind(person1);
newlogname1(); // prints 'Cristiano Ronaldo'

var newlogname2 = logname.bind(person2);

newlogname2(); // prints 'Cristiano Ronaldo'

var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}

var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}


var logname = function() {
console.log(this.getName());
}.bind(person1); // not working as expected when .bind() here !!!


var newlogname1 = logname.bind(person1);
newlogname1(); // prints 'Cristiano Ronaldo'

var newlogname2 = logname.bind(person2);

newlogname2(); // prints 'Cristiano Ronaldo'

但是如果我更改下面的代码片段,它将按我的预期工作。

var logname = function() {
console.log(this.getName());
};

var person1 = {
fname: 'Cristiano',
lname: 'Ronaldo',
getName: function() {
return this.fname + ' ' + this.lname;
}
}

var person2 = {
fname: 'Luka',
lname: 'Modric',
getName: function() {
return this.fname + ' ' + this.lname;
}
}


var logname = function() {
console.log(this.getName());
};

var newlogname2 = logname.bind(person2);
newlogname2();

var newlogname1 = logname.bind(person1);
newlogname1();

这是什么行为?当我 .bind() 时会发生什么只是在它的声明部分。我不能改变什么this应该意味着当函数运行时,如果我这样做的话。

最佳答案

.bind() 仅在您要绑定(bind)的函数尚未绑定(bind)时才有效:

function f() {
console.log(this.a)
}

const f_1 = f.bind({a: 1}) // As expected
const f_2 = f.bind({a: 2}) // -Ditto-
const f_2_3 = f_2.bind({a: 3}) // f_2 already bound, can't .bind() to other object

f_1()
f_2()
f_2_3()

/** Check if function is bound, as per @str's comment */
function isBound(fun) {
return !('prototype' in fun)
}

console.log(
isBound(f),
isBound(f_1)
)

更新:添加了检查函数是否已绑定(bind)的方法,按照@str's comment下面

关于javaScript .bind() 不会返回一个新函数,该函数在调用时将具有等于我传递的 arg 的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com