关于在JavaScript中向对象添加方法的说明?
在以下函数中,函数内部有一个名为关于在JavaScript中向对象添加方法的说明?,javascript,Javascript,在以下函数中,函数内部有一个名为newlastname的方法: 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)
newlastname
的方法:
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代码>发生了什么?第一个newlastname指的是什么?非常感谢您提供的任何提示或建议。在这行代码中:
this.newlastname=newlastname;
第一个newlastname
是person
对象上的属性
第二个newlastname
是对newlastname()
函数的引用
因此,当您这样做时:
this.newlastname=newlastname;
您正在person
对象的属性中存储对该函数的引用。这将允许以下代码工作:
var p = new person("Ted", "Smith", 31, "blonde");
p.newlastname("Bundy");
当您执行p.newlastname(“Bundy”)
,它将在名为newlastname
的person
对象上查找属性。当它找到该属性时,它将执行该函数并将其传递给“Bundy”
,并将此
设置为特定的人
对象。在这行代码中:
this.newlastname=newlastname;
第一个newlastname
是person
对象上的属性
第二个newlastname
是对newlastname()
函数的引用
因此,当您这样做时:
this.newlastname=newlastname;
您正在person
对象的属性中存储对该函数的引用。这将允许以下代码工作:
var p = new person("Ted", "Smith", 31, "blonde");
p.newlastname("Bundy");
当您执行p.newlastname(“Bundy”)
,它将在名为newlastname
的person
对象上查找属性。当它找到该属性时,它将执行该函数并将其传递给“Bundy”
,并将this
设置为特定的person
对象。当在函数内部执行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));
当您在函数(所有函数都是对象)内部执行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));
太棒了-现在点击了!非常感谢你!太棒了-现在点击了!非常感谢你!