javascript对象的几种创建方式

1.工厂模式

function createBlog(name, url) {
  var o = new Object();
  o.name = name;
  o.url = url;
  o.sayUrl= function() {
    alert(this.url);
  }
  return o;
}
var blog1 = createBlog('wuyuchang', 'http://www.jb51.net/');
alert(blog1);

2.构造函数模式

function Blog(name, url) {
  this.name = name;
  this.url = url;
  this.alertUrl = function() {
    alert(this.url);
  }
}
 
var blog = new Blog('wuyuchang', 'http://www.jb51.net/');
alert(blog instanceof Blog);

3.原型模式

function CreateJsPerson(name, age) {
    this.name = name;
    this.age = age;
}

CreateJsPerson.prototype.writeJs = function () {
    console.log(this.name + ' write js');
};

var p1 = new CreateJsPerson('iceman' , 25);
var p2 = new CreateJsPerson('mengzhe' , 27);
    
console.log(p1.writeJs === p2.writeJs);

4.混合构造函数和原型模式

function Blog(name, url, friend) {
  this.name = name;
  this.url = url;
  this.friend = friend;
}
Blog.prototype.alertInfo = function() {
  alert(this.name + this.url + this.friend);
}
var blog = new Blog('wuyuchang', 'http://tools.jb51.net/', ['fr1', 'fr2', 'fr3']),
  blog2 = new Blog('wyc', 'http://**.com', ['a', 'b']);
blog.friend.pop();
blog.alertInfo(); 
blog2.alertInfo();

5.动态原型模式

function Blog(name, url) {
  this.name = name;
  this.url = url;
  if (typeof this.alertInfo != 'function') {
    // 这段代码只执行了一次
    alert('exe time');
    Blog.prototype.alertInfo = function() {
      alert(thia.name + this.url);
    }
  }
}
var blog = new Blog('wuyuchang', 'http://tools.jb51.net'),
  blog2 = new Blog('wyc', 'http:***.com');

6.寄生构造函数模型

function SpecialArray()  
{  
    var value=new Array();  
    value.push.apply(value,arguments);  
    value.toPipedString=function()  
    {  
       return this.join("|");  
}  
  return value;  
}  
SpecialArray();

7.稳妥构造函数模型

function Process (nameF) {
    var o = new Object();
    var name = nameF;//1
    o.sayName = function(){
        alert(name);//2
    };
    return o;
}

var friend = Process('Nick');
friend.sayName();  //"Nick"
console.log(friend.name);//undefined//3

你可能感兴趣的:(javascript对象的几种创建方式)