@Dale-Lin
2022-03-08T06:54:55.000000Z
字数 1401
阅读 660
JavaScript
在一个函数(在非严格模式)被调用时,this 作为默认的参数传递。
this 在 JavaScript 中的值取决于函数调用的模式。(运行时绑定)
一个函数作为一个对象的属性时,称为一个方法。
如果调用表达式包含一个.,则是作为某对象的属性调用的方法。
作为方法调用时,this 绑定在该对象上。
此时,方法中使用 this 可以访问自己所属的对象。
const a = {name: 'a',sayThis: () => {console.log(this) // 声明语句所处的 this 是 Window}}const b = {name: 'b',sayThis() {console.log(this)}}a.sayThis() // Windowb.sayThis() // bb.sayThis = a.sayThisb.sayThis() // Window
当一个函数不作为一个对象的属性时,则作为一个函数调用。
非严格模式:函数调用时的 this 绑定到全局对象(window/globalThis)。
严格模式:this 为 undefined。
如果在闭包中需要访问外部函数的上下文,必须将外部函数的 this 保存在变量中,再在闭包中用该变量替换。否则闭包中直接使用的 this 将指向全局变量:
myObj.double = function(){var that = this;var helper = function(){that.value = add(that.value, that.value);}helper(); //函数形式调用}
class Animal {sayThis() {console.log(this)}static sayDees() {console.log(this)}}Animal.sayDees() // class Animalconst a = new Animal()a.sayThis() // Animal a// 类实例的方法相当于启用了严格模式let copy = a.sayThiscopy() // undefinedcopy = Animal.sayDeescopy() // undefined
使用 new 操作符调用函数时,会创建一个连接到该函数的 prototype 对象的新对象。
此时新对象内的 this 绑定在这个新对象上。
var Quo = function(str){this.status = str;};Quo.prototype.get_status = function(){return this.status;};var myQuo = new Quo("confused");myQuo.get_status(); //"confused"
使用函数的 apply() 或 call() 调用的时候,this 会绑定在这两个方法的第一个参数上。
call() 方法接受单独的参数;apply() 方法接受一个参数数组。
