js中创建对象的5种方法

1、原始模式

var  dog  =    {
    name: jack,
    length: 70,
    wang:function(){
        console.log(this.name);
    }

2、工厂模式(批量)

function  creatdog  (name,length) {
    var  moudle  =   new  object ();
    dog.name=name;
    dog.length=length;
    dog.wang=function(){
        console.log(this.name);
    };
    return moudle;
}

3、构造函数

function  Dog (name,length) {
    this.name=name;
    this.length=length;
    this.wang=function() {
        console.log(this.name);
    };
}
var dog1 = new Dog( 'wangcai' , 80) //创建一个dog1对象

Dog('wangcai', 80);    //属性方法都给window对象,window.name='wangcai',window.wang()会输出wangcai

4、原型模式

function  Dog () {}
Dog.prototype.name = 'wangcai';
Dog.prototype.length=80;
Dog.prototype.wang= function () {
    console.log(this.name);
};

var  dog1 = new Dog();
// dog1:name:'wangcai';length:80;f:wang()

5、混合模式

function Dog (name, length) {
 
    this.name = name;
 
    this.length = length;
 
}
 
Dog.prototype = {
 
    hobby: ['running','eat'];
 
    wang: function () { 
    console.log(this.name);
   } };
var dog1 = new Dog('wangcai', 80); //dog1:'wangcai',80; __proto__: ['running','eat'],wang var dog2 = new Dog('defu', );70 //dog2:'defu',70;__proto__: ['running','eat'],wang

 

posted on 2018-12-23 21:52  jswzy  阅读(539)  评论(0编辑  收藏  举报