Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

this的绑定规则总结 #68

Open
JesseZhao1990 opened this issue Mar 11, 2018 · 1 comment
Open

this的绑定规则总结 #68

JesseZhao1990 opened this issue Mar 11, 2018 · 1 comment

Comments

@JesseZhao1990
Copy link
Owner

JesseZhao1990 commented Mar 11, 2018

如果要判断一个运行中函数的this绑定,就需要找到这个函数的直接调用位置,找到之后就可以顺序应用下面的这四条规则来判断this的绑定对象

  • 1.由new调用?绑定到新创建的对象。
  • 2.由call或者apply(或者bind)调用?绑定到指定的对象。
  • 3.由上下文对象掉用?绑定到那个上下文对象。
  • 4.默认:在严格模式下绑定到undefined,否则绑定到全局对象。

ES6中的箭头函数并不会使用四条标准的绑定规则,而是根据当前的词法作用域来决定this,具体来说,箭头函数会继承完成函数调用的this绑定。

@JesseZhao1990
Copy link
Owner Author

一个扩展题目

掌握了this的绑定规则之后,来思考一下。如何实现一个bind函数?

Function.prototype.bind = function(content){
  let that = this;
  let arg = Array.prototype.slice.call(arguments,1);
  return function(){
    let thisArg = arg.concat([...arguments]);
    that.apply(content,thisArg)
  }
}

function Person(name,age,sex){
  console.log(this.name)
  console.log(name)
  console.log(this.age)
  console.log(age)
  console.log(this.sex)
  console.log(sex)
}

var person1 = {
  name:'zhangsan',
  age:22,
  sex:'male'
}

Person = Person.bind(person1,'lisi')
Person(80,'female')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant