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

JavaScript 对象的创建方式

2018-03-09 17:35 204 查看
JavaScript中所有对象来自于Object
工厂模式
坏处:无法判断返回的对象是什么类型function people(name,age,work){
var man= new Object();
man.name=name;
man.age=age;
man.work=work;
man.getMan=function(){
alert(this.name);
}
return man;
}
var people1 = people('Tom',18,'student');构造函数模式
与工厂模式相比:没有return语句 可以识别对象类型 没有显示创建对象 直接指向this对象

function People(name,age,work){ //注意第一个首字母大写
this.name=name;
this.age=age;
this.work=work;
this.getName=function(){
console.log(this.name);
}
}
var people1= new People('jerry',20,'student');

原型模式
Object.prototype.constructor 特定的函数,用于创建一个对象的原型
function People(){

};
People.prototype.name='Lily';
People.prototype.age=18;
People.prototype.work='singer';
People.prototype.getPeople=function(){
console.log(this.name);
}
var people1=new People();
console.log(people1.name); //Lily
var people2=new People();
console.log(people2.name); //Lilyprototype属性,是一个指针指向一个对象
当构造一个对象(people1)后,他的默认属性name就是Lily。
混合模式
混合模式就是原型加上构造函数function People(name,age,work){
this.name=name;
this.age=age;
this.work=work;
}
People.prototype={
constructor: People,
getName:function(){
console.log(this.name);
}
}
var people1= new People('Lily',18,'student');
console.log(people1); //{name: "Lily", age: 18, work: "student"}最大限度的节省了内存 构造函数用于定义属性 原型用于定义和共享
动态原型模式
将所有信息封装在构造函数内 而通过构造函数中初始化原型 function People(name,age){
this.name=name;
this.age=age;
if(typeof this.human!="function"){
console.log('Tom');
People.prototype.human=function(){
console.log('名字'+this.name+'年龄'+this.age);
}
}
}
var people1= new People('Lily',18);
//console.log Tom
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: