【javascript】创建对象的几种方式

来源:互联网 发布:淘宝延期收货是几天 编辑:程序博客网 时间:2024/05/16 12:30

1.工厂模式

function createPerson(name, age, job){    var o = new Object();    o.name = name;    o.age = age;    o.job = job;    o.sayName = function(){        alert(this.name);    };    return o;}var person = createPerson("Greg", 27, "Doctor");

2.构造函数模式

//构造函数首字母大写function Person(name, age, job){    this.name = name;    this.age = age;    this.job = job;    this.sayName = function(){        alert(this.name);    };}//当做构造函数使用var person = new Person("Greg", 27, "Doctor");person.sayName(); // "Greg"//作为普通函数调用Person("Greg",27,"Doctor");window.sayName(); // "Greg"//使用new操作符来调用构造函数,则创建新对象,并且属性和方法都赋给指定的对象,如果不用new操作符,则将属性和方法赋给window对象。

3.原型模式

我们创建的每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。

function Person(){}Person.prototype.name = "Greg";Person.prototype.age = 29;Person.prototype.job = "Doctor";Person.prototype.sayName = function(){    alert(this.name);}var person = new Person();person.sayName();

通过原型模式创建的对象,所有的属性都是一样的 。

4.动态原型模式

该模式是把所有信息都封装到构造函数中,通过构造函数中初始化原型(仅在必要的情况下),又保持了同时使用构造函数和原型的优点

function Person(name, age, job){    this.name = name;    this.age = age;    this.job = job;    if(typeof this.sayName != "function"){        Person.prototype.sayName = function(){            alert(this.name);        }    }}var friend = new Person("Greg",20,"Doctor");frient.sayName();
0 0
原创粉丝点击