gpt4 book ai didi

javascript - 关于在 JavaScript 中向对象添加方法的澄清?

转载 作者:行者123 更新时间:2023-11-28 21:05:37 25 4
gpt4 key购买 nike

在以下函数中,其中有一个名为 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; 行中发生了什么?第一个新姓氏指的是什么?我很感激任何提示或建议。

最佳答案

在这行代码中:

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对象。 p>

关于javascript - 关于在 JavaScript 中向对象添加方法的澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9958494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com