zoukankan      html  css  js  c++  java
  • apply bind call 和 this

    Javascript里面的this由调用方式确定它的指向。

    1. 函数

    此时为this为window

            function log()
            {
                console.log(this);
            }
            log();
    

     

    2. 对象方法

    此时为实例对象。

            function log()
            {
                console.log(this);
            }
    
            function class1()
            {
                this.name="class1 name"
            }
    
            var obj1=new class1();
            obj1.fu1=log;
            obj1.fu1();
    

    但我们可以通过使用apply,bind,call来指定'this'.

            function log()
            {
                console.log(this);
            }
            log.call({name:"test call"});
            log.apply({name:"test apply"});
            log.bind({name:"test bind"})()
    

    下面是一个简单的bind实现,可以帮助理解。

            Function.prototype.bind2 = function(context){
                var _that = this;
                return function()
                {
                    _that.apply(context);
                };
            }
    
            function fn1()
            {
                console.log(this);
            }
    
            var fn2=fn1.bind2({name:"testing"});
            fn2();
    

     

    ------------------------------------------------------------
    如非注明都是原创,如需转载请注出处。
  • 相关阅读:
    #1071 : 小玩具
    #1063 : 缩地
    #1124 : 好矩阵
    hiho#1145 : 幻想乡的日常
    hiho#14
    hiho 毁灭者问题
    西南民大oj(递推)
    西南民大oj(矩阵快速幂)
    西南民大oj(两园交求面积)
    hdu2844(多重背包)
  • 原文地址:https://www.cnblogs.com/Ivan83/p/9114559.html
Copyright © 2011-2022 走看看