js面向对象设计模式

2019-03-18  本文已影响0人  原来如此scater

1、工厂模式

function createPerson(name, age, job){
    const o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
       alert(this.name);
    };
    return o;
}
const scater = createPerson("scater", 29, "web前端");

2、构造函数模式

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function(){
       alert(this.name);
    };
}
const scater = new Person("scater", 29, "web前端");

3、原型模式

function Person(){}
Person.prototype.name = "scater";
Person.prototype.age = 29;
Person.prototype.job = "web前端";
Person.prototype.sayName = function(){
   alert(this.name);
};
const scater = new Person();
scater.sayName(); // "scater "

4、组合使用构造函数模式和原型模式

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby", "Court"];
}
Person.prototype = {
    constructor : Person,
    sayName : function(){
        alert(this.name);
    }
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
alert(person1.friends); //"Shelby,Count,Van"
alert(person2.friends); //"Shelby,Count"
alert(person1.friends === person2.friends); //false
alert(person1.sayName === person2.sayName); //true

5、动态原型模式

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);
        };
    }
}
const scater = new Person("scater", 29, "web前端");
scater.sayName(); // "scater"

6、寄生构造函数模式
除了使用 new 操作符并把使用的包装函数叫做构造函数之外,这个模式跟工厂模式其实是一模一样的。

function Person(name, age, job){
    const o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function(){
        alert(this.name);
    };
    return o;
}
const scater = new Person("scater", 29, "web前端");
scater.sayName(); // "scater"

7、稳妥构造函数模式
稳妥对象,指的是没有公共属性,而且其方法也不引用 this 的对象。稳妥对象最适合在一些安全的环境中(这些环境中会禁止使用 this 和 new ),或者在防止数据被其他应用程序(如 Mashup程序)改动时使用。稳妥构造函数遵循与寄生构造函数类似的模式,但有两点不同:一是新创建对象的实例方法不引用 this ;二是不使用 new 操作符调用构造函数。按照稳妥构造函数的要求。

function Person(name, age, job){
    //创建要返回的对象
    const o = new Object();
    //可以在这里定义私有变量和函数
    //添加方法
    o.sayName = function(){
        alert(name);
    };
    //返回对象
    return o;
}
const scater = Person("scater", 29, "web前端");
scater.sayName(); // "scater"

在以这种模式创建的对象中,除了使用 sayName() 方法之外,没有其他办法访问 name 的值。

上一篇下一篇

猜你喜欢

热点阅读