zoukankan      html  css  js  c++  java
  • 渡一 13-2 this指向

    1.函数预编译过程this->window
    2.全局this->window
    3.call/apply改变this指向
    4.obj.func();func()里的this指向obj

    function test(c){
        //var this = Object.create(test.prototype);
        //__proto__:test.prototype
        var a=123;
        function b(){}
    }
    
    AO{
        arguments:[1],
        this:window,
        c:1,
        a:undefined,
        b:function(){}
    }
    
    test(1);
    //new test();

    练习题

    1.
    var obj = {
        a:function(){
            console.log(this.name);
        },
        name:'abc'
    }
    obj.a(); //abc
    
    2.
    var name = "222";
    var a={
        name:"111",
        say:function(){
            console.log(this.name);
        }
    }
    var fun=a.say;
    fun();
    a.say();
    
    //output:222 111
    
    var b={
        name:"333",
        say:function(fun){
            fun();
        }
    }
    b.say(a.say); //重点:这里执行的是fun();不是this.fun();所以是全局this
    b.say = a.say;
    b.say();
    
    //output:222 333
    var foo='123';
    function print(){
        var foo='456';
        this.foo="789";
        console.log(foo);
    }
    print();//456
    
    
    var foo=123;
    function print(){
        this.foo = 234;
        console.log(foo);//this.foo->234
    }
    print();//234
    new print();//123
    
    
    1.运行test()和new test()的结果分别是什么?
    var a = 5;
    function test(){
        a=0;
        console.log(a);
        console.log(this.a);
        var a;
        console.log(a)
    }
    test()
    //test output:0 5 0
    //new test output:0 undefined 0
    
    
    function print(){
        var marty = {
            name:"marty",
            printName:function(){console.log(this.name);}
        }
        var test1 = {name:"test1"};
        var test2 = {name:"test2"};
        var test3 = {name:"test3"};
        test3.pirntName = marty.printName;
        var printName2 = marty.printName.bind({name:123});
        marty.printName.call(test1);//test1
        marty.printName.apply(test2);//test2
        marty.printName();//marty
        printName2();
        test3.printName();//test3
    
    }
    
    
    var bar = {a:"002"};
    function print(){
        bar.a="a";
        Object.prototype.b="b";
        return function inner(){
            console.log(bar.a);
            console.log(bar.b);
        }
    }
    print()();
    //output:a b
  • 相关阅读:
    Django 数据库常用字段类型、选项参数、外键约束
    Django 项目基础配置
    MySQL连接列值
    SQL 限制查询结果
    python+appium+真机测试
    P3089 [USACO13NOV]POGO的牛Pogo-Cow
    P2889 [USACO07NOV]挤奶的时间Milking Time
    P2679 子串
    P3932 浮游大陆的68号岛
    P1514 引水入城
  • 原文地址:https://www.cnblogs.com/lisa2544/p/15302985.html
Copyright © 2011-2022 走看看