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

标签 javascript

我有以下代码。

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/

相关文章:

javascript - 数组语法错误新手

javascript - 我可以将 JavaScript 对象存储在 mySQL 数据库中吗?

javascript - jQuery 原型(prototype)冲突 : table filter plugin

javascript - 在 JavaScript 中拆分字符串并检测换行符

javascript - 在 PHP 或 JavaScript 中防止多次点击提交多个表单

javascript - 正则表达式捕获引号后跟非标点字符

javascript - Typeahead.js Bloodhound 忽略高质量结果

javascript - 仅当元素存在时才使用 Jquery 函数(Ajax 调用)

javascript - 我如何访问javascript中的 Action 传递的参数?

JavaScript - 从文本中选择单词