隐式绑定
const user = {
name: '张三',
age: 18,
say(){
document.write(`hi,我叫${this.name},今年18岁了`);
}
}
user.say(); // this -> user
显式绑定
const user = {
name: '张三',
age: 18
}
function say(arg1, arg2, arg3){
document.write(`hi,我叫${this.name},今年${this.age}了,我会${arg1}、${arg2}和${arg3}...`);
}
const skill = ['HTML', 'CSS', 'JavaScript'];
say.call(user, ...skill); // this -> user
// say.apply(user, skill); // this -> user
// say.bind(user, ...skill)(); // this -> user
new 关键字绑定
function user(name, age) {
/**
* JavaScript 会在底层创建一个新对象 `this`,它会代理不在 User 原型链上的属性。
* 如果一个函数用 new 关键字调用,this 就会指向解释器创建的新对象。
* **/
this.name = name;
this.age = age;
document.write(`hi,我叫${this.name},今年${this.age}了`);
}
const me = new user('张三', 18);
window绑定
window.name = '张三';
window.age = 18;
const skill = ['HTML', 'CSS', 'JavaScript'];
function say(arg1, arg2, arg3) {
document.write(`hi,我叫${this.name},今年${this.age}了,我会${arg1}、${arg2}和${arg3}...`);
}
say(...skill); // this -> window
注:如果是严格模式的话,JavaScript 不会默认将 this 指向 window 对象,而会将 this 正确的保存为 undefined。
最后
要知道 this 是什么,可以根据以下几种情况来判断
1、首先查看函数在哪被调用
2、函数是不是作为对象的属性调用的(如:obj.fn/obj['fn']),如果是,它就是 “this” 的引用。如果没有,继续第 3 步。
3、该函数是不是用 “call”、“apply” 或者 “bind” 调用的?如果是,它会显式地指明 “this” 的引用,call、apply、bind的第一个参数。如果不是,继续第 4 步
4、该函数是不是用 “new” 调用的?如果是,“this” 指向的就是 JavaScript 解释器新创建的对象。如果不是,继续第 5 步
5、是否在“严格模式”下?如果是,“this” 就是 undefined,如果不是,继续第 6 步
6、如果都不是,那么 JavaScript 会默认将 “this” 指向 “window” 对象