call、apply和bind的⽤法及区别⼀、call和apply
1、call和apply都是function.prototype的⽅法,每⼀个⽅法的对象实例 new function()都会有这两个属性;
2、这两个属性都是针对⽅法的属性针对⽅法使⽤;
3、call和apply使⽤⽅法相同;
4、call和apply的参数不同;
(1)test.call ( this, param1 , param2 , param3 ) ; // 可以传多个参数
(2)test.apply ( this, paramArray ) ; // 只能传两个参数,第⼆个⼀般为数组
⼆、bind
call和apply会改变this指向,然后执⾏函数;
bind会改变this指向后,返回⼀个绑定新this的函数;
三、demo
var name = "aven";
var age = 18;
var obj = {
name: "ake",
age: this.age,
test: function(){
console.log("name: ", this.name, "age: ", this.age );
}
};
// name: ake age: undefined
/
/ 因为st() 只会调⽤本⾝属性,本⾝没有age属性,但是有name属性
// name: aven age: 18
// call参数为null或undefined时默认指向window,
// this含有属性 name : "aven", age: 18,所以输出结果变化
var name = "testName";
var age = 18;
var obj = {
name: "ake",
age: this.age,
test: function(gender, home){
console.log("name: ",this.name,"age:",this.age,"gender:",gender,"home: ", home);
}
};
var person = {
name: "aven",
age: 18
}
四、实现call⽅法
Call = function () {
var _this = arguments[0]
var params = [...arguments].slice(1)
var isStrict = (function () {return this === undefined})typeof的用法
if (!isStrict) {
// 如果是其他原始值,需要通过构造函数包装成对象
var type = typeof _this;
if (type === 'number') {
_this = new Number(_this)
} else if (type === 'string') {
_this = new String(_this)
} else if (type === 'boolean') {
_this = new Boolean(_this)
}
}
var invokeFun = this;
if (_this === null || _this === undefined) {
return invokeFunc(...params)
}
var uniquePropName = Symbol(_this)
_this[uniquePropName] = invokeFun
return _this[uniquePropName](...params)
}
五、实现⼀个apply,跟call相似,把参数列表改为参数数组Apply = function (_this, params) {
var isStrict = (function() {return this === undefined}())
if (!isStrict) {
// 如果是其他原始值,需要通过构造函数包装成对象
var type = typeof _this;
if (type === 'number') {
_this = new Number(_this)
} else if (type === 'string') {
_this = new String(_this)
} else if (type === 'boolean') {
_this = new Boolean(_this)
}
}
var invokeFun = this
var invokeParams = Array.isArray(params) ? params : []
if (_this === null || _this === undefined) {
return invokeFun(...invokeParams)
}
uniquePropName = Symbol(_this)
_this[uniquePropName] = invokeFun
return _this[uniquePropName](...invokeParams)
}
六、实现bind,区别在于
Bind = function() {
var boundTargetFunc = this;
if (typeof boundTargetFunc !== 'function') {
throw new Error('绑定的⽬标必须是函数')
}
var boundThis = arguments[0];
var boundParams = [].slice.call(arguments, 1);
function fBound () {
var restParams = [].slice.call(arguments);
var allParams = at(restParams)
return boundTargetFunc.apply(this instanceof fBound ? this : boundThis, allParams)
}
fBound.prototype = ate(boundTargetFunc.prototype || Function.prototype)
return fBound
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论