1. 程式人生 > >關於js作用域問題

關於js作用域問題

cti col 函數 UNC 問題 nbsp pan fun test

補充:

function Foo(name,age){
    this.name=name;
    this.age=age;
    this.getName=function(){
        console.log(this);
    }
        
}

obj = new Foo("文州",19)
obj.getName()    
//這裏把Foo看成類,大寫是類,首字母小寫是函數


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

test()=== window.test()
//函數執行相當於window.test().所以打印的this是window對象。

(
function(){ console.log(this) })() 這個叫自執行函數。this指的還是window。 題目0 var name="女神" function Foo(name,age){ this.name=name; this.age=age; this.getName=function(){ console.log(this); (function(){ console.log(this.name) //自執行函數裏面是window對象 })() } } obj
= new Foo("文州",19) obj.getName() 第一次打印文州,第二次打印女神 想要都打印文州的話 題目1 var name="女神" function Foo(name,age){ this.name=name; this.age=age; this.getName=function(){ console.log(this); var that =this //把當前環境的this賦值給that.那麽這樣2個都打印文州 (function(){ console.log(that.name)
})() } } obj = new Foo("文州",19) obj.getName() //這樣2個都執行文州。
題目2
var name="女神" obj={ name:‘文州‘, age:19, getName:function(){ console.log(this); var that =this (function(){ console.log(that.name) })() } } obj.getName() //這個結果和上面的一樣。只是(對象)的聲明方式改變了而已。

關於js作用域問題