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();
    

     

    ------------------------------------------------------------
    如非注明都是原创,如需转载请注出处。
  • 相关阅读:
    php (一)
    php 运算符
    Python 元组
    Python 深拷贝和浅拷贝的区别
    Python 列表
    Python 字符串
    Python 循环控制
    Python 随机数,数学
    bzoj5018 [Snoi2017]英雄联盟
    bzoj5015 [Snoi2017]礼物
  • 原文地址:https://www.cnblogs.com/Ivan83/p/9114559.html
Copyright © 2011-2022 走看看