Javascript创建对象 -- 构造函数模式

时间:2014-10-08 16:37:45   收藏:0   阅读:148
 1 function Person(name, age) {
 2     this.name = name;
 3     this.age = age;
 4     this.eat = function() {
 5         alert("eating...");
 6     }
 7 }
 8 var p1 = new Person("cai10", 21);
 9 var p2 = new Person("cai20", 27);
10 alert(p1.name);                 // cai10
11 alert(p1.age);                  // 21
12 p1.eat();                       // eating...
13 alert(typeof p1);               // object
14 alert(p1 instanceof Object);    // true
15 alert(p1 instanceof Person);    // true
16 alert(p1.constructor);          // function Person(name, age) {...}
17 alert(p1.eat == p2.eat);        // false

通过new关键字, 创建并返回一个新的对象. 
在Person()中, 没有显示的创建对象, 
而是直接将属性和方法赋给了this对象, 也没有return语句. 
使用构造函数模式创建实例, 可以将该实例标识为一种特定的类型, 
如例子中, 使用instanceof操作符或constructor属性可以得到验证. 
但仍旧有存在多个Function实例的问题. 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!