1、工厂模式
function createObj(name,age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function(){
return this.name + this.age
}
return obj;
}
var box1 = createObj("Yang",24);
alert(box1.run()); // Yang24
2、构造函数(推荐)
function CreateObj(name,age){
this.name = name;
this.age = age;
this.run = function(){
return this.name + this.age;
}
}
var box1 = new CreateObj("Yang",24);
alert(box1.run()); // Yang24
3、字面量形式
function box(){};
box.prototype = {
constructor : box, //强行指向对象
name : "Yang",
age : 24,
run : function(){
return this.name + this.age
}
}
var box1 = new box();
alert(box1.run());
继承:
1、原型链继承
function Box(){ // 父类
this.name = "Yang";
}
function Desk(){ // 子类
this.age = 24;
}
Desk.prototype = new Box(); // 父类实例化赋值给子类继承
var Desk = new Desk();
alert(Desk.name);
2、对象冒充继承
function Box(name,age){
this.name = name;
this.age = age;
}
Box.prototype = function(){
this.family = [1,2,3];
}
function Des(name,age){
Box.call(this,name,age);//对象冒充继承
}
var Desk = new Desk("Yang",24);
alert(Desk.name);// Yang
alert(Desk.age);// age Box的属性赋值就继承过来了
alert(Desk.family);// undefined 对象冒充继承,只能继承对象实例里面的方法和属性,// 如果要实例化属性和原型一起继承,需要配合第一种方法一起使用 </span>
解决办法:
在调用之前加上:Desk.prototype = new Box(); // 父类实例化赋值给子类继承</span>
</pre><pre name="code" class="javascript">
PS:删除对象属性和方法(删除原型属性也一样可以)
delete Desk.name;