在 javascript 之 this 关键字详解文章中, 谈及了如下内容, 做一个简单的回顾:
1.this 对象的涵义就是指向当前对象中的属性和方法.
2.this 指向的可变性. 当在全局作用域时, this 指向全局; 当在某个对象中使用 this 时, this 指向该对象; 当把某个对象的方法赋值给
另外一个对象时, this 会指向后一个对象.
3.this 的使用场合有: 在全局环境中使用; 在构造函数中使用, 在对象的方法中使用.
4.this 的使用注意点, 最重要的一点就是要避免多层嵌套使用 this 对象.
对 this 关键字有了稍稍了解便知道, this 对象指向会经常改变的, 这会造成一些意想不到的影响. JavaScript 提供了 call,apply,bind 这三个方法, 来切换 / 固定 this 的指向. 下面的主要划分:
1.call/apply/bind 方法的来源
- Function.prototype.call
- Function.prototype.apply
3.1: 找出数组中的最大数
3.2: 将数组的空元素变为 undefined
3.3: 转换类似数组的对象
4.Function.prototype.bind
5. 绑定回调函数的对象
6.call,apply,bind 方法的联系和区别
1.call/apply/bind 方法的来源
首先, 在使用 call,apply,bind 方法时, 我们有必要知道这三个方法究竟是来自哪里? 为什么可以使用的到这三个方法?
call,apply,bind 这三个方法其实都是继承自 Function.prototype 中的, 属于实例方法.
- console.log(Function.prototype.hasOwnProperty('call'))//true
- console.log(Function.prototype.hasOwnProperty('apply'))//true
- console.log(Function.prototype.hasOwnProperty('bind')) //true
- 111
来源: http://www.bubuko.com/infodetail-2751829.html