代码一:
this.number = 10function a() { ?this.number = 20}a.prototype.init = () => console.log(this.number)const test = new a() // 构造函数成一个独立新对象test.init() // 10
解析:之所以输出10,可以把 arrow function(箭头函数) 里的 this 和 arguments 关键字,可理解为函数作用域里的变量,他访问变量沿着作用域链向上找而不是访问对象属性走原型链,代码中的init上头的作用域就是window,所以他的this指向window.
代码二:
this.number = 10function a() { ?this.number = 20 ?}a.prototype.init = function() { ?return () => console.log(this.number) // 闭包函数}const test = new a()test.init() // 20
NO1. this
this的指向可理解为两大类:
1:test();==test.call(window,参数);//直接调用函数,this指向window
2:obj.test(); == obj.test.call(obj,参数);//函数作为对象的方法被调用,this指向该对象
注:this指向是在被调用时分配的
关于js里的this指向,函数的prototype,闭包理解
原文地址:https://www.cnblogs.com/xiaoxiao666/p/8350617.html