调用和绑定链如何在内部工作?

时间:2018-09-12 08:49:14

标签: javascript

我有一个程序,其功能为Person,greet,specificCall,对象为kumar和chandra。

var fullName=""
function greet() {
    console.log("Welcome "+ this.fullName);
}
var Person=function (name) {
    this.fullName=name
    console.log(this.fullName)
}
var chandra=new Person("chandrakumar")
var kumar=new Person("kumar")
var specificCall=function(){
    console.log("Dude "+ this.fullName);
}
var newGreeting=Person.call.bind(specificCall)// I don't understand the meaning here
newGreeting()// logs Dude 
newGreeting(kumar)//logs Dude kumar How is this happening

我认为Person.call是一个函数,因为我已经检查了Personof.call的类型,而specificCall又是一个函数。如何将功能绑定到功能? 尽管我不小心编写了这段代码,但我不理解其逻辑? Person.call会触发构造函数,而newGreeting会触发specificCall函数。如果仔细观察,则newGreeting(kumar)等同于specificCall.apply(kumar)。在这里,不仅改变了范围的上下文,而且改变了整个功能本身。就像specificCall绑定到Person.call一样?

1 个答案:

答案 0 :(得分:0)

Call允许您在激活函数时设置函数执行的范围,默认为window

//Set global variable to fallback to
var fullname = "Window";
//Set local variable
var person = {
    fullname: "Bob"
};
//Definer caller object
function logObject() {
    //"this" references current scope
    console.log(this.fullname);
}
//Call with nothing, defaulting to global
logObject.call();
//Call with specific object as scope
logObject.call(person);

Bind设置功能的范围,但不激活它。

//Set global variable to fallback to
var fullname = "Window";
//Set local variable
var person = {
  fullname: "Bob"
};
//Definer caller object
function logObject() {
  //"this" references current scope
  console.log(this.fullname);
}
//Bind with nothing, defaulting to global
var logger1 = logObject.bind();
//Execute
logger1();
//bind with specific object as scope
var logger2 = logObject.bind(person);
//Execute
logger2();

据我所知,您bind specificCallcall上的Person,这意味着触发newGreeting与运行{{ 1}},但以Person.call作为绑定范围。

这不是漂亮的代码,我个人会建议一个更具可读性的结构:

specificCall