繁体   English   中英

有关在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;

第一个newlastnameperson对象上的一个属性。

第二个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM