关于在JavaScript中向对象添加方法的说明

Clarification about adding a method to an object in JavaScript?

本文关键字:添加 方法 说明 对象 JavaScript      更新时间:2023-09-26

在下面的函数中,其中有一个名为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));