![](/img/trans.png)
[英]what 's the difference about adding the new method to an object in javascript?
[英]Clarification about adding a method to an object in 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)
{
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");
,它将在person
对象上查找名为newlastname
的属性。 当它发现属性,则执行该功能,并将它传递"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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.