zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    夜半饮酒
    邀你到成都来
    成都,我的天堂
    真不想松开你的手
    创业,你懂如何求人办事么?
    只要你愿意
    【五月的歌】重振山河
    成都,我爱你
    就算忘了自己也忘不了你
    假如
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/5003677.html
Copyright © 2011-2022 走看看