2012-03-31 44 views
0

在下面的函数,用它里面的方法称为newlastname在JavaScript中向对象添加方法的说明?

function person(firstname,lastname,age,eyecolor) 
{ 
    this.firstname=firstname; 
    this.lastname=lastname; 
    this.age=age; 
    this.eyecolor=eyecolor; 

    this.newlastname=newlastname; 
} 


function newlastname(new_lastname) 
{ 
    this.lastname=new_lastname; 
} 

在线路this.newlastname=newlastname;发生了什么?第一个新名称是指什么?我很欣赏任何提示或建议。

回答

2

在这行代码:

this.newlastname=newlastname; 

第一newlastnameperson对象上的属性。

第二个newlastname是对newlastname()函数的引用。

所以,当你这样做:

this.newlastname=newlastname; 

你是存储在person对象的属性给函数的引用。这将使下面的代码工作:

var p = new person("Ted", "Smith", 31, "blonde"); 
p.newlastname("Bundy"); 

当您执行p.newlastname("Bundy");,它会寻找名为newlastnameperson对象上的属性。当它找到该属性时,它将执行该功能,并将其传递给"Bundy",并将其设置为person对象的特定this

+0

真棒 - 现在点击!非常感谢你! – Coffee 2012-03-31 18:36:40

1

当你在一个函数内部(所有函数都是对象)做this.x = x时,第一个x就成为该对象的一个​​属性。因此,您可以在对象内的任何位置执行this.x以访问其值。例如 -

function test (x) 
    { 
     this.x = x + 2; // the first x is an property of test. the second is the passed argument 
     return this.x; 
    } 

    console.log(test(2)); // 4 

,你也可以做以下检查测试的所有属性和方法

console.log(new test(2));