天天看点

js创建对象

1. 对象字面量

var obj={
    name:'syl',
    height:'175',
    say:function(){
        console.log('hello');
    }
}      

缺点:只能创建一次对象,复用性较差,如果要创建多个对象,代码冗余度太高

2. 内置构造函数

2.1 直接使用Object();

var obj=new Object({
    name:'syl',
    height:'175',
    say:function(){
        console.log('hello');
    }
});      

2.2 封装Object()—工厂模式

function createObj(name,height){
    var obj=new Object({
        name:'syl',
        height:'175',
        say:function(){
            console.log(this.name);
        }
    });
    return obj;
}      

缺点:对象无法识别,因为所有的实例都指向一个原型。

3. Object.create()

var p = {
    name:'syl',
    height:'175',
    say:function(){
        console.log(this.name);
    }
};
var obj = Object.create(p);      

4 构造函数

function P(name,height){
    this.name=name;
    this.height=height;
    this.say=function(){
        console.log(this.name);
    };
}
var obj=new P('syl','175'); 
obj.sayHeight()=function(){
    console.log(this.height);
}      

缺点:构造函数中定义函数,那么每次创建对象,都会重新创建该函数,这样会导致全局变量增多。

原型

function P(name,height){
    this.name=name;
    this.height=height;
}
P.prototype.say=function(){
    cosole.log(this,name);
}

var obj=new P('syl','175'); 
p.say();
      

将函数放到原型中,解决了构造函数方法的缺点。

继续阅读