关于在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));
相关文章:
- 在对象中添加方法时出现问题
- 什么意思是“;向原型添加方法”;
- jQuery验证器添加方法未定义
- 向通过ReST JSON调用生成的Angular Javascript对象添加方法
- 向React中的高阶组件添加方法
- 向JavaScript对象添加方法
- 如何向[]添加方法
- 如何在流星js中为对象添加方法
- jQuery.validation 在生日年龄验证中添加方法错误
- 使用 IE8 添加方法的 JavaScript 错误
- 向方法添加方法
- 如何在 Javascript ES6 中向类添加方法
- Javascript:向对象类添加方法的优缺点是什么
- 如何更改“动物”的原型并添加方法“sayName”来打印语句
- 如何在 Illustrator CS5.1+ 中创建画板对象的添加方法所需的矩形对象
- 如何在 nodejs 中全局添加方法到 JSON、Date 或其他“本机”对象
- 什么类/类型是未定义的,是否可以向其扩展/添加方法
- 为什么在 javascript 中向数组原型添加方法会破坏 for 循环上的迭代
- 向对象添加方法
- 动态添加方法到对象