一、this指针指向module.exports
console.log("全局中的this指向的是module.exports");console.log(this); //{}this.obj = "Hello World";console.log(this.obj); //Hello Worldconsole.log(global.obj); //undefinedconsole.log(module.exports.obj); //Hello Worldconsole.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 Worldconsole.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); //globalconsole.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); //1998console.log(global.year); //undefinedconsole.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>显示>隐式");