this -> JS 关键字
当前环境执行期上下文
this在不同的环境,不同作用下,表现不同
全局作用域下this —> 全局对象
window 和 this 的关系
web —> window
node —> global
worker —> self
通用 —> globalThis
谁调用函数,函数内容的执行默认就是谁
类的this
类的本质就是函数
class xxx -> 容器/作用域/模块
类是严格模式
class Test1(){constructor(){}static do(){}say(){}}const Test = (function () {function Test2(){ // constructor}Test.prototype.say = function (){}Test.prototype.do = function (){}window.Test = Test;})();class Test {constructor(){// 类的非静态方法 -> new -> this -> {} -> test方法和age属性this.age = 22;this.test = function(){}}// 类原型上的静态方法 -> Test.prototype{...}test(){}}// 继承class Father {constructor(){// 基类 no this binding, 因为没实例没调用//new -> this -> {} -> age属性this.age = 44;}swim() {console.log('swimming');}}class Son extends Father {constructor(){// 调用Father上的constructor// 生成this绑定 -> Father this -> son的实例上// this -> new Father() -> {}super();this.name ='son';}study(){this.swim();}}
call/apply/bind this
var newFn = function test(a,b,c) {
this ->window ->context
}.bind(context);
bind与call/apply区别:
bind不会立即执行函数,而是返回一个新的函数,这个新的函数绑定上下文(context)
call/apply 立即执行函数,并且将this指向改为context
var initModule = (function(){return {a: 1,b: 2,plus: function() {return this.a + this.b;}})(); // 立即执行函数,执行完返回一个对象,对象赋值给initModuleconsole.log(initModule) // {a:1,b:2,plus:f}var obj = {a: 1}var obj2 = {a:100}var a = 2;function test(){// this 默认 -> 全局对象windowconsole.log(this.a)}test();test.call(obj);test.apply(obj);//bind 只生效一次var test1 = test.bind(obj,3,4);test1(); //1,3,4var tes2 = test.bind(obj,3,4);test2(); // 1,3,4
箭头函数中的this
var obj = {a: 1}var a = 2;const test = () => {consloe.log(this.a);}test();//2// 箭头函数是忽略任何形式的this指向的改变// 静态this指向test.call(obj); //2test.apply(obj); //2var test1 = test.bind(obj); //2test1();// 箭头函数一定不是一个构造器new test(); //报错// 箭头函数的this不是谁绑定指向谁obj.test = () => {console.log(this); // window}// 箭头函数 this -> 外层作用域的this指向
对象的this
this 的指向的基本原则: 谁调用this的宿主,this就指向谁
对象方法的内部this -> 最近的引用
把t函数是一个孤立的函数
new
function Test(){// new过程// this-> {}// { a: 1 }// { a:1, b:2 }// return thisthis.a = 1;this.b = 2;console.log(this);//默认 return this;// return { c:3, d:4} // 忽略return this}new Test(); // -> { a:1, b:2 }
事件处理函数中的this
事件(onclick)处理函数内部的this指向被绑定DOM元素
oBtn.addEventListener('click', this.handleBtnClick.bind(this), false);
