javascript中对象的创建-构造函数模式

function Person(name,age,job){
    this.name=name;
    this.age=age;
    this.job=job;
    this.sayName=function(){
        alert(this.name);
    };
}    
var person1=new Person("null",25,"Software Engineer");
var person2=new Person("null2",250,"Software Engineer");

与工厂模式区别:

1.没有显式创建对象

2.直接将属性和方法赋给了作用域

3.没有return语句

构造函数模式的创建步骤:

1.创建一个新对象

2.将构造函数的作用域赋值给新对象(因此this就指向了这个新对象)

3.执行构造函数中的代码(为这个新对象添加属性)

4.返回新对象

alert(person1.constructor==Person);//true
alert(person2.constructor==Person);//true

alert(person1 instanceof Object);//true
alert(person1 instanceof Person);//true
alert(person2 instanceof Object);//true
alert(person2 instanceof Person);//true

  创建自定义的构造函数意味着将来可以将它的实例标识为一种特定的类型,这里是Person,这正是构造函数模式胜过工厂模式的地方,当然,它们同时Object的实例(所有对象均继承自Object).

 

posted on 2014-04-08 22:52  nU||  阅读(196)  评论(0编辑  收藏  举报

导航