2014-08-29 44 views
0

爲什麼this.age = age;age = this.age不同。第二個是未定義的。在以下代碼中爲javascript添加新屬性(此)關鍵字

代碼:

function person(firstname,lastname,age,eyecolor) { 
    this.firstname = firstname; 
    this.lastname = lastname; 
    //this.age = age; 
    age = this.age; 
    this.eyecolor = eyecolor; 
    this.changeName = changeName; 
    function changeName(name) { 
     // this.lastname = name; 
     name = this.lastname; 
    } 
} 
var myMother = new person("Sally","Rally",48,"green"); 
myMother.changeName("Doe"); 
document.getElementById("demo").innerHTML = 
"My mother's last name is " + myMother.lastname; 

如果我們改變的變化不會發生的順序name = this.lastname

+0

因爲'this'沒有屬性'age',你需要在設置它之前設置它。 – levi 2014-08-29 21:08:06

+3

你的問題是什麼?你爲什麼期望兩種不同的事情做同樣的事情? – 2014-08-29 21:08:22

+0

@levi「this.lastname」呢? – arash 2014-08-29 21:12:21

回答

2

當您使用this它指的是當前對象的範圍。 age截至此刻爲age即將通過,但this.age從未定義。所以你不妨設置age = undefined

this.age是對象person()的一部分。 age是您傳遞給對象的值。

this.age; //undefined 
age=5;//5 
this.age;//undefined 
age = this.age;// undefined for both 
this.age=7;//7 
age;//undefined 
age=this.age;//both equal 7 

沒有this.age變量都在下面的例子中

function bob(){ 
     this.age; 
    } 

    function smith(){ 
     this.age; 
     var smithSelf = this;//i just created a value smithSelf that is equal to this inside of smith() so smithSelf is pointing to smith() 
     function lastTime(){ 
      this.age;//this is lastTime() this.age value. 
      smithSelf.age;//this is smith() this.age value. 
     } 
    } 

同樣給出下面的一個person(age){}是在側()通過age是你傳遞的值。this.age不與您通過的值age相同。

function person(age){ 
    this.age; 
} 

如果您仍然對this感到困惑,那麼您可能需要閱讀編程範圍。所有OOP語言都有一個通常稱爲this的範圍值,它指的是「此範圍」。

給出示例a=b您將最終將a設置爲值b。所以如果b未定義,則a現在將是未定義的。如果你想b等於a那麼你會做b=a。當一個對象,你做this.b,你在價值a通過,並讓說,如果你做a=this.ba設置爲5你會從過去的例子注意到this.b被創建,但你從來沒有設置一個值,它使this.b是未定義。所以現在在這一點你設置a等於this.b所以現在a是未定義的。

如果您對操作順序感到困惑,只需簡單地說出等式。 a=b「A等於B」,然後你就會明白爲什麼左邊的值被設置爲右邊的值。

+0

,感謝您的支持,但在第二種情況下'this.lastname'在函數的外部定義,但在對象 – arash 2014-08-29 21:38:29

+0

內部,這是指當前對象。當你改變範圍時,這將意味着你每次都在對象的範圍內。如果我有兩個對象鮑勃和史密斯這兩個年齡和史密斯年齡不平等。 – 2014-08-29 21:41:05

+0

,我只是想檢查一下我是否正確。在我的問題代碼'this.lastname = name;'(this)是爲函數chnageName,當我們改變命令'name = this.lastname;'那裏沒有this.lastname定義 – arash 2014-08-29 22:02:14