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
  • 相关阅读:
    PHP touch() 函数
    PHP tmpfile() 函数
    PHP tempnam() 函数
    PHP symlink() 函数
    PHP stat() 函数
    pt-table-sync
    P4233 射命丸文的笔记
    C# Task.Run 和 Task.Factory.StartNew 区别
    C# Task.Run 和 Task.Factory.StartNew 区别
    SourceYard 制作源代码包
  • 原文地址:https://www.cnblogs.com/scnuwangjie/p/5003677.html
Copyright © 2011-2022 走看看