通过构造函数创建对象
来自CloudWiki
使用构造函数
本例使用构造函数来构造对象:
实例
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
在JavaScript中,this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)
创建 JavaScript 对象实例
一旦您有了对象构造器,就可以创建新的对象实例,就像这样:
var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green");
完整代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <script> function person(firstname,lastname,age,eyecolor){ this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } myFather=new person("John","Doe",50,"blue"); document.write(myFather.firstname + " is " + myFather.age + " years old."); </script> </body> </html>
把属性添加到 JavaScript 对象
您可以通过为对象赋值,向已有对象添加新属性:
假设 person 对象已存在 - 您可以为其添加这些新属性:firstname、lastname、age 以及 eyecolor:
person.firstname="John"; person.lastname="Doe"; person.age=30; person.eyecolor="blue"; x=person.firstname;
在以上代码执行后,x 的值将是:
John
把方法添加到 JavaScript 对象
方法只不过是附加在对象上的函数。
在构造器函数内部定义对象的方法:
function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName; function changeName(name) { this.lastname=name; } }
changeName() 函数 name 的值赋给 person 的 lastname 属性。
完整代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <script> function person(firstname,lastname,age,eyecolor){ this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName; function changeName(name){ this.lastname=name; } } myMother=new person("Sally","Rally",48,"green"); myMother.changeName("Doe"); document.write(myMother.lastname); </script> </body> </html>