Object构造函数构建
1 2 3 4
| var person = new Object(); person.name = "zyx"; person.age = 20; alert(person.name); // zyx
|
对象字面量表示法
1 2 3 4 5 6
| var person = {}; var person = { name: 'zyx'; age: 20; 5: 5; };
|
相对来说形式更简单一些,我们访问name值时,可以用person.name,但是访问5这个值的时候,必须使用person[5]
工厂模式
1 2 3 4 5 6 7 8 9 10
| function createPerson(name, age) { var o = new Object(); o.name = name; o.age = age; o.sayname = () { alert(this.name); }; return o; } var person1 = createPerson('zyx', 20);
|
构造函数
1 2 3 大专栏 四种对象表示法/>4 5 6 7 8
| function Person(name,age) { this.name = name; this.age = age; this.sayname = () { alert(this.name); }; } var person1 = new Person('zyx', 20);
|
原型创建对象
1 2 3 4 5 6 7 8
| function Person() {} Person.prototype.name = 'zyx'; Person.prototype.age = 20; Person.prototype.sayname = (){ alert(this.name); }; var person1 = new Person(); person1.sayname();
|
组合使用
1 2 3 4 5 6 7 8 9 10 11
| function Person(name, age) { this.name = name; this.age = age; } Person.prototype = { constructor: Person, sayName: () { alert(this.name); }; } var person1 = new Person('zyx', 20);
|