mbufxa
Last Updated: February 25, 2016
·
501
· richardgong1987
Psb  1

javascript OOP design

Create javascript Ojbect

1, the factory pattern

function factoryObject(name, age, id) {
  var object = new Object();
  object.name = name;
  object.age = age;
  object.id = id;
  object.sayName = function() {
    alert(this.name)
  }
  return object;
}
console.log(factoryObject('richard','26','123456'));//{name: "richard", age: "26", id: "123456", sayName: function}

2,the constructor pattern

function constructorObject(name, age, id) {
  this.name = name;
  this.age= age;
  this.id =id;
  this.showName = function  (argument) {
    alert(this.name)
  }
}

console.log(new constructorObject('richard','26','123456'));//constructorObject {name: "richard", age: "26", id: "123456", showName: function}

3,the prototype pattern

function prototypeObject(argument) {

}
prototypeObject.prototype.name = 'richardgong';
prototypeObject.prototype.age = 26;
prototypeObject.prototype.id = 123645;
prototypeObject.prototype.showName = function() {
    alert(this.name);
}

var newprotoObject = new prototypeObject;
console.log(newprotoObject);//prototypeObject {name: "richardgong", age: 26, id: 123645, showName: function}

4, Combination Constructor/Prototype Pattern;

function Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    this.frinds = ['a', 'b', 'c'];
}
Person.prototype = {
    constructor: Person,
    sayName: function(argument) {
        alert(this.name)
    }
}
var person1 = new Person('richard',26, 'enginner');
var person2 = new Person('rcihardgong', 27, 'development');
person1.frinds.push('aaaaaaaaaaaaaaaa');

console.log(person1, person2);           

5,Parasitic Constructor Pattern

function arr(argument) {
    var v = new Array();
    v.push.apply(v, arguments);
    v.show = function(argument) {
        return this.join("|");
    }
    return v;
}
var vv = new arr('richard','gong', '123456');
console.log(vv);// ["richard", "gong", "123456", show: function]
Say Thanks
Respond