-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
this、call和apply #2
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why
JS编程中,
this
关键字经常会让人迷惑,Function.prototype.call
和Function.prototype.apply
这两个方法也有这广泛的应用同时它们也是面试过程中的常客
this
JS中的this总是指向一个对象,具体指向哪个对象是在运行时基于函数的执行环境动态绑定的,而非函数被声明时的环境。
从上面的描述可以得知,只有函数中才存在this
this的指向
this的指向大致分为以下4种
1. 作为对象的方法调用
当函数作为对象的方法被调用时,this指向该对象
2. 作为普通函数调用
当函数不作为对象的属性被调用时,也就是普通函数方式,此时的this总是指向全局变量。
在浏览器的JavaScript里,这个全局对象是window对象。
在ES5的
strict
模式下,这种情况下的this已经被规定不会指向全局对象,而是undefined3. 构造器调用
除了宿主提供的一些内置函数,大部分JS函数都可以被当作构造器使用。
构造器的外表和普通函数一摸一样,区别在于被调用的方式。当用new运算符调用该函数时,
会返回一个对象。通常情况下,构造器的this就指向返回的这个对象
特殊情况下,如果构造器显式的返回一个object类型的对象,那么此次运算会返回这个对象,而不是我们之前期待的this
如果构造器不显式的返回任何数据,或者是返回一个非对象类型的数据,就不会造成上述问题。
4. Function.prototype.call或Function.prototype.apply
和普通函数相比,这两个函数可以动态的改变传入函数的this
call和apply能很好的体现JS的函数式语言特性。
5.ES6中箭头函数的this
箭头函数里面 this 始终指向外部对象,因为箭头函数没有 this,因此它自身不能进行new实例化,同时也不能使用 call, apply, bind 等方法来改变 this 的指向。
丢失的this
call和apply
call和apply的区别
call和apply作用一样,区别仅在于传入参数的形式不同。
thisArg: 指定了函数体内this对象的指向
argsArray: 为一个带下标的集合,这个集合可以是数组,也可以为类数组(array-like object)。apply把这个集合中的元素作为参数传给被调用的函数
thisArg: 指定了函数体内this对象的指向
arg1, arg2 ...: 每个参数会依次传入函数
call和apply的用途
1. 修正this指向
2. Function.prototype.bind
Function.prototype.bind的实现
3. 借用其他对象的方法
场景A 借用构造函数实现继承
场景B 操作类数组
V8引擎中Array.prototype.push的具体实现
可以看出,Array.prototype.push根本不管被修改的对象是数组还是类数组对象,只要在里面追加属性(下标)是合法的和修改length可读写,就可以把任意对象传入Array.prototype.push
可以借用Array.prototype.push方法的对象至少要满足的两个条件
例如,number类型的数据无法存取数据,function类型的数据length属性只读不可写,
它们都无法借用到Array.prototype.push方法
The text was updated successfully, but these errors were encountered: