您的位置:首页 > Web前端 > JavaScript

JS创建对象

2015-10-25 15:12 429 查看
本人常用的创建对象的方式,仅供参考,欢迎吐槽,谢谢!

创建对象
1、对象字面量,即使用大括号,如下:

(function(){

var obj = {
id: 1,
desc: '创建对象测试开始啦!',
show: function(){
console.log("id=%d, desc=%s", this.id, this.desc);
}
};

obj.show();
})();


2、构造函数

(function(){

function Animal(name, age){
this.name = name;
this.age = age;
this.show = function(){
console.log("该动物是%s,今年%d岁", this.name, this.age);
}
}

var cat = new Animal('猫咪', 3);
cat.show();

})();


一种错误:

(function(){

function Animal(){
}

Animal.prototype.name = '猫咪';
Animal.prototype.age = 3;
Animal.prototype.show = function(){
console.log("该动物是%s,今年%d岁", this.name, this.age);
};

animal = Animal();
animal.show();//TypeError: animal is undefined

})();


解决方案

(function(){

function Animal(){
if( !(this instanceof Animal) ){
return new Animal();
}
}

Animal.prototype.name = '猫咪';
Animal.prototype.age = 3;
Animal.prototype.show = function(){
console.log("该动物是%s,今年%d岁", this.name, this.age);
};

animal = Animal();
animal.show();//该动物是猫咪,今年3岁

})();


3、原型模式

(function(){

function Animal(){

}

Animal.prototype.name = '猫咪';
Animal.prototype.age = 3;
Animal.prototype.show = function(){
console.log("该动物是%s,今年%d岁", this.name, this.age);
};

var animal = new Animal();
animal.show();//该动物是猫咪,今年3岁

animal.name = "狗熊";
animal.age = 14;
animal.show();//该动物是狗熊,今年14岁

delete animal.name;
animal.show();//该动物是猫咪,今年14岁

})();


备注:当删除对象的属性时,为啥从该对象的name,从狗熊变成了猫咪了呢?这是跟JS中属性的查找有关!首先其先从该对象的属性中查找若有,则立即返回,当没有,再到其原型中查找,若有则立即返回,最后当找不到时,则返回undefined

什么是原型?

1、我们创建的每一个函数都有一个prototype属性,这个属性是一个对象,它的用途是包含有特定类型的所有实例共享的属性和方法。
2、只要创建了一个新函数,就会为该函数创建一个prototype属性。默认情况下,所有prototype属性都会自动获得一个constructor属性,这个属性包含一个指向prototype属性所在函数的指针。这样,函数以及函数原型之间就形成了循环指向了。
3、每当调用构造函数创建一个新实例后,该实例的内部将包含一个指针(一般指__proto__),指向构造函数的原型属性。

参考资料:

有图的,很有意思:http://www.cnblogs.com/maxupeng/archive/2010/12/28/1918480.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: