this指向
指代当前调用的这个对象
4中绑定(优先级从低到高):
- 默认绑定
- 隐式绑定
- 显示绑定
- new绑定
var person = { name: 'Tom', age: 23, showName: function () { // this->person console.log(this.name); // Tom }, showAge: function () { // 局部函数 function _age(){ // this->window console.log(this.age); // undefined } _age(); // this->person console.log(this.age); // 23 }, }; person.showName() person.showAge()
可以先保存this
let that = this;
改变this指向
call/apply/bind
var name = 'Tom' var person = { name: 'Jack', showName: function(){ console.log(this.name); } } person.showName(); // Jack // this->window var show = person.showName; show(); // Tom var fn = person.showName.bind(person); fn(); // Jack
实现一个bind方法
Function.prototype.bind = function(obj){ var that = this; return function(){ that.apply(obj) } } // 验证 var name = 'Tom' var person = { name: 'Jack', showName: function(){ console.log(this.name); } } var fn = person.showName.bind(person); fn(); // Jack1. Function.prototype