1、this指針指向module.exports
console.log("全局中的this指向的是module.exports");
console.log(this); //{}
this.obj = "Hello World";
console.log(this.obj); //Hello World
console.log(global.obj); //undefined
console.log(module.exports.obj); //Hello World
console.log("-------------------------------------------------------" + "\n\n");
2、this指針指向global對象
console.log("在函數中this指向的是global對象,和全局中的this不是同一個對象");
function fn() {
this.obj = "good good study! day day up!";
}
fn();
console.log(this);//{ obj: 'Hello World' }
console.log(this.obj);//Hello World
console.log(global.obj);//"good good study! day day up!"
console.log("-------------------------------------------------------" + "\n\n");
console.log("在函數中this指向的是global對象,和全局中的this不是同一個對象");
function fn1() {
function fn2() {
this.msg = "I love you";
}
fn2();
console.log(this); //global
console.log(this.msg); //"I love you"
console.log(global.msg); //"I love you"
}
fn1();
console.log("-------------------------------------------------------" + "\n\n");
3、在構造函數中this指向的是它的實例,而不是global
function Fn3(){
this.year = 1998;
}
let fn3 = new Fn3();
console.log(this); //{ obj: 'Hello World' }
console.log(fn3.year); //1998
console.log(global.year); //undefined
console.log("-------------------------------------------------------" + "\n\n");
4、this指針顯式、隱式傳遞與綁定
console.log("顯式傳遞this");
let Kirito = {};
function person(name, sex, age, addr, salary) {
this.name = name;
this.sex = sex;
this.age = age;
this.addr = addr;
this.salary = salary;
}
//這裏的傳入Kirito爲this指針所指向的對象
//使用.call()進行顯式傳遞
person.call(Kirito, "桐人",
"男",
18,
"SAO",
999999999);
console.log(Kirito);
console.log("-------------------------------------------------------" + "\n\n");
console.log("隱式傳遞this");
let Ausua = {
name: "亞絲娜",
sex: "女",
age: 18,
addr: "SAO",
salary: 999999999,
func() {
console.log(this);
},
func_bind: function () {
console.log(this);
}.bind("綁定")
};
Ausua.func();
console.log("-------------------------------------------------------" + "\n\n");
console.log("強制綁定this指針");
let func = function () {
console.log(this);
}.bind(Kirito);
func();
console.log("-------------------------------------------------------" + "\n\n");
console.log("注意:\n\t這裏的func是在原來的對象基礎上,使用bind綁定了this指針,產生了新的函數對象!");
func = function () {
console.log(this);
};
//注意:func此時綁定對象後,func變量的對象引用指針 指向綁定前
func.bind(Kirito);
func();
//注意:func此時綁定對象後,func變量的對象引用指針 指向綁定後
func = func.bind(Kirito);
func();
console.log("-------------------------------------------------------" + "\n\n");
5、this指針顯式、隱式傳遞與綁定的優先級
let priority = function () {
console.log(this);
};
console.log("綁定優先於隱式");
Ausua.func_bind();
console.log("-------------------------------------------------------" + "\n\n");
console.log("綁定優先於顯式");
priority = priority.bind("綁定");
priority.call("顯式");
priority();
console.log("-------------------------------------------------------" + "\n\n");
console.log("顯式優先於隱式");
Ausua.func.call("顯式");
console.log("-------------------------------------------------------" + "\n\n");
console.log("結論:優先級:bind>顯示>隱式");