例说 JS 继承之对象冒充
来源:互联网 发布:观星软件 安卓 编辑:程序博客网 时间:2024/05/16 16:11
<!DOCTYPE html><html><head> <title>JS继承之对象冒充</title> <script type="text/javascript"> function ClassA(sColor) { this.color = sColor; this.sayHello = function AsayHello(){ alert("Hello from ClassA ! --" + this.color); }; }; function ClassB(){ this.name = "B"; alert(this.name + " <==1==> " + this.color); // B <==1==> undefined 因还未继承 this.newMethod = ClassA; /* 此时ClassA 中的this 实际上是指当前 ClassB 的实例! this.newMethod = ClassA; 的等价代码如下: this.newMethod = function ClassA(sColor){ this.color = sColor; //此行此时 this 已经为ClassB 的实例 this.sayHello = function AsayHello(){ //此行此时 this 已经为ClassB的实例 alert("Hello from ClassA ! --" + this.color); }; */ this.newMethod("red"); //当前的ClassB对象(this)已经通过继承获得 sayHello 方法类型的属性和 color 属性 this.sayHello(); // Hello from ClassA ! --red alert(this.name + " <==2==> " + this.color); // B <==2==> red /* 删除了对ClassA的引用,这样以后就不能再调用它。 所有的新属性和新方法都必须在删除了新方法的代码行后定义。 否则,可能会覆盖超类的相关属性和方法。 */ delete this.newMethod; // 删除对 ClassA 的引用后,还能成功获得color 值,表明继承是成功的! alert(this.name + " <==3==> " + this.color); // B <==3==> red }; new ClassB().sayHello(); //AsayHello 是不可见的,不能在此使用! </script></head><body> <H1>对象冒充</H1> <p> 对象冒充是在函数环境中使用this关键字后发展出来的一种继承方式。</P> <P>其原理如下: 构造函数使用this关键字给所有属性和方法赋值(即采用类声明的构造函数方式)。因为构造函数只是一个函数,所以可使ClassA的构造函数成为ClassB的方法,然后调用它。ClassB就会收到ClassA的构造函数中定义的属性和方法 </P></body></html>