其他分享
首页 > 其他分享> > 渡一 this指向

渡一 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

 

标签:function,渡一,console,name,指向,test,var,log
来源: https://www.cnblogs.com/lisa2544/p/15302985.html