JS 创建对象

工厂模式(未解决对象识别问题)

function createPerson(name,age,job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson("Joe",22,"doctor");
var person2 = createPerson("May",21,"teacher");

构造函数模式

function Person(name,age,job){   //Person首字母大写
//无需显示创建对象
//直接将属性和方法赋给this对象
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){   //每个方法要在每个实例上重新创建一遍  解决方法 将函数转移到构造函数外部 但是这样函数都是全局函数 无封装性可言
alert(this.name);
};
//无return语句
}
//new操作符来创建对象 就像var o = new Object(); 一样
var person1 = new Person("Joe",22,"doctor");
var person2 = new Person("May",21,"teacher");


原型模式


function Person(){
}
Person.prototype.name = "Joe";
Person.prototype.age = 29;
Person.prototype.job = "teacher";
Person.prototype.sayName = function(){
alert(this.name);
};
//Person.prototype={
//name : "Joe",
//age : 29,
//job : "teacher",
//sayName : function(){
//alert(this.name);
//};
var person1 = new Person();
var person2 = new Person();
person1.name = "May";
alert(person1.name); //May----来自实例
alert(person2.name); //Joe-----来自原型
alert(person1.hasOwnProperty("name")); //true 检测一个属性是否存在实例中
alert(person2.hasOwnProperty("name")); //false
delete person1.name;
alert(person1.name); //May-----来自原型


组合使用构造函数模式和原型模式

function Person(name,age,job){   
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Bob","Emily"]; //对象可分别引用不同的数组
}
Person.prototype = {
constructor:person,
sayName:function(){
alert(this.name);
}
}

 
  


你可能感兴趣的:(javascript)