call()
使用方法: _fun.call(obj,…args);
参数: 第一个参数是函数运行时将指向的this,第二个参数放置了一些参数,call方法需要将其逐个列出;
作用: 改变执行函数的作用域为传入call的第一个参数对应的作用域
使用示例:
let obj = { name: "_call应用" };
function _fun(args){
console.log(this.name,...args);
}
_fun.call(obj,'参数2') // _call应用 参数2
原理:
这里有几个需要注意的点:
1、若call()第一个参数为空,则表示调用call方法的函数的this将指向window
2、若call()没有第二个参数,可直接执行指定this后的方法;
3、在将this指向第一个参数时需要保证fn是唯一的
方法如下:
function _callFun(){
const fn = Symbol("fn"); //保证fn的唯一性
let args = [];
for (let i = 0; i < arguments.length; i++) {
if (i > 0) {
args.push(arguments[i]);
}
}
obj = obj || window;
obj[fn] = this; // 这里的this表示了当前函数作用域,而当外部函数调用该方法时,this就指向了调用这个函数的那个函数
if (!args) {
return obj[fn]();
} else {
return obj[fn](args);
}
};
let obj = { name: "_call应用" };
function _fun(args){
console.log(this.name,...args);
}
_fun._apply1(obj, "我传参啦1"); // _call应用 我传参啦1
}
apply()
apply
与call的
作用是一样的,他们的区分就在于第二个参数,apply
中第二个参数为一个数组,保存了所有需要传给调用方的参数;
使用示例:
let obj = { name: "_apply应用" };
function _fun(args){
console.log(this.name,...args);
}
_fun.call(obj,['参数2']) // _apply应用 参数2
原理
apply的实现与call基本一样,唯一的不同就在第二个参数的处理。
function _applyApplication() {
Function.prototype._apply1 = function (obj, args) {
const fn = Symbol("fn"); //保证fn的唯一性
obj = obj || window;
obj[fn] = this; // 这里的this表示了当前函数作用域,而当外部函数调用该方法时,this就指向了调用这个函数的那个函数
if (!args) {
return obj[fn]();
} else {
return obj[fn](args);
}
};
let obj = { name: "_apply应用" };
let _applyFun = function(args){
console.log(this.name, ...args);
}
_applyFun._apply1(obj, ["我传参啦"]); // _apply应用 我传参啦
},
bind()
bind方法与call的作用基本一样,他的区别在于调用bind后将会生成一个实例;
使用示例:
function _bindApplation(){
let obj = { name: "bind应用" };
let _fun = function(args){
console.log(this.name);
}
let _bindFun = _fun.bind(obj);
_bindFun(); // bind应用
}
原理
可使用apply或者call实现
function _bindApplation(){
Function.prototype._bind = function (obj) {
let _this = this;
return function () {
return _this.apply(obj)
}
}
let obj = { name: "bind应用" };
let _fun = function(args){
console.log(this.name);
}
let _bindFun = _fun._bind(obj);
_bindFun(); // bind应用
}