一、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");
二、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");
三、在组织函数中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");
四、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");
五、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>显现>隐式");