例说 JS 继承之对象冒充

<!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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值