您的位置:首页 > Web前端 > JavaScript

JS 创建对象(常见的几种方法)

2014-10-24 13:38 661 查看
参考 : /article/1260368.html

//1.工厂模式

function createPerson(name, age, job) {
    var o = {};
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function() {
        alert(this.name);
    };
    return o;
}
var tanya = new Person("tanya", "30", "female");
var ansel = new Person("ansel", "30", "male");
tanya.sayName();
ansel.sayName();






/*

*2.构造函数方法

*因为this就表示当前运行时的对象,将构造函数this的作用域指向新对象,

*将当前运行对象的属性和方法都赋给新对象,这样对象模式称为构造函数模式

*/

function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function() {
        alert(this.name);
    };
}
var tanya = new Person("tanya", "30", "female");
var ansel = new Person("ansel", "30", "male");
tanya.sayName();
ansel.sayName();




//3.原型链

//原型模式就要考虑原型链了,分析一下,sayName方法在实例中被重复定义了两次,

//但其实没有必要创造两个一样的副本。

//使用原型方法,可以使得tanya和ansel的共享一个sayName方法。

function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
}
Person.prototype.sayName = function() {
    alert(this.name);
};
var tanya = new Person("tanya", "30", "female");
var ansel = new Person("ansel", "30", "male");
tanya.sayName();
ansel.sayName();




/*4. 实际应用时,不是一成不变的套用某种模式,活学活用。

1)需要共享方法的时候就用原型模式,

2)需要使用副本的时候就用构造模式,

3)还可以结合起来,把所有信息都封装在构造函数中,而通过在构造函数中初始化原型,

使得对象保持了同时使用构造函数和原型的优点。 */

function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    if (typeof sayName != "function") {
        Person.prototype.sayName = function() {
            alert(this.name);
        };
    }
}
var tanya = new Person("tanya", "30", "female");
var ansel = new Person("ansel", "30", "male");
ansel.sayName = function() {
    alert("Hi ansel, how hansome you are!");
}
tanya.sayName();
ansel.sayName();
tanya.sayName();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: