javascript 对象基础 继承机制实例【对象冒充】

面向对象语言 必须支持继承机制,既一个类能重用另一个类的方法和属性.

1、继承方式

  • 对象冒充

工作原理:构造函数使用this关键字,给所有属性和方法赋值,因为构造函数值只是一个函数,所以可以使ClassA的构造函数成为ClassB的方法 。然后调用它,ClassB就会收到ClassA的构造函数中定义的属性和方法。考虑下面例子

function ClassA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color)
}
};
function ClassB(sColor){
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
this.newMethod = "miss"; //删除了不能再调用
}
var b = new ClassB("red");
b.sayColor(); // output "red";

这段代码中 , 为ClassA 赋予了方法  newMethod .然后调用了新方法. 传递给它的是 ClassB构造函数的参数 sColor. 最后一行代码删除了对ClassA的引用. 这样以后就不能再调用它.

所有新的属性和方法都必须在删除了新方法(newMethod)的代码行后定义,否则可能会覆盖(ClassB)相关的属性和方法.

function ClassA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color)
}
};
function ClassB(sColor,sName){
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
var a = new ClassA("red");
var b = new ClassB("blue","idea");
a.sayColor();
b.sayColor();
b.sayName();
posted @ 2012-01-04 10:03  noyobo  阅读(300)  评论(0编辑  收藏  举报