首页 > Web开发 > 详细

js借用和绑定

时间:2015-11-29 00:32:16      阅读:387      评论:0      收藏:0      [点我收藏+]
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

 

js借用和绑定

原文:http://www.cnblogs.com/scnuwangjie/p/5003677.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!