js借用和绑定

时间:2023-03-08 20:48:32
js借用和绑定
var one = {
name:"object",
say:function(greet) {
return greet + ","+this.name;
}
}
//console.log(one.say("hi")); //结果hi,object
var two = {
name:"another"
};
console.log(one.say.apply(two,["hello"])); //结果hello,another

借用say()方法内部的this指向了two对象。

但是在如果将函数指针复制给一个全局变量,或者将该函数作为回调函数来传递,整个代码就可能不会像预期那样运行。如下:

//给变量赋值,“this”将会指向全局变量
var say = one.say;
console.log(say("you")); //结果you,undefined //作为回调函数使用
var yetanother = {
name:"yet",
method:function(callback){
return callback("HOHO");
}
}
console.log(yetanother.method(one.say));//结果HOHO,undefined

这时候可以使用下面一个函数来解决

function bind(o,m){
return function(){
return m.apply(o,[].slice.call(arguments));
}
}

可以使用上面的函数绑定对象和需要借用的方法。

var twoSay = bind(two,one.say);
console.log(twoSay("jie")); //jie,another