关于在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));

太棒了-现在点击了!非常感谢你!太棒了-现在点击了!非常感谢你!