javascript 创建对象

1、原型模式创建对象

(1)第一种
function Newperson(){
    
}

var person2 = new Newperson();


Newperson.prototype.name = 'tom';
Newperson.prototype.age = 22;
Newperson.prototype.job = 'teacher';
Newperson.prototype.sayName = function(){
    alert(this.name);
}

var person1 = new Newperson();

console.log(person1.constructor);//Newperson()

console.log(person2.constructor);//Newperson()

(2)第二种

function Person(){
    
}

var friend = new Person();

//用一个包含所有属性和方法的对象字面量重写原型对象,相当于重写了Newperson的prototype对象
Person.prototype = {
        //constructor:Person,//添加这句,可以使 person.constructor 指向 Person
        name:'tom',
        age:22,
        job:'teacher',
        sayName:function(){
            alert(this.name);
        }
}

var person = new Person();

console.log(friend.constructor);//Person()
console.log(person.constructor);//Object()

 

 2、寄生构造函数模式创建对象
    //eg1
    function Animal(name, age, voice){
        var o = new Object();
        o.name = name;
        o.age = age;
        o.voice = voice;
        o.sayVoice = function(){
            return this.voice;
        }
        return o;
    }
    
    var cat = new Animal('喵咪', 2, 'miao');
    console.log(cat.name);//喵咪
    console.log(cat.sayVoice());//miao
    
    //eg2
    function Specialarray(){
        var values = new Array();
        values.push.apply(values, arguments);
        values.toPipedString = function(){
            return this.join('|');
        }
        return values;
    }
    
    var array1 = new Specialarray('a', 'b', 'c');
    console.log(array1.toPipedString());//a|b|c
    console.log(array1.constructor);//Array()
    console.log(array1 instanceof Object);//true

  这种模式创建的对象与构造函数或者构造函数的原型属性之间没有关系,不能依赖instanceof 来确定对象类型。建议可以在使用其他模式的情况下不要使用这种模式。

posted @ 2015-12-04 15:46  tianxintian22  阅读(207)  评论(0编辑  收藏  举报