• JavaScript组合继承的一点思考


    今天看《JavaScript高级程序设计》一书中关于组合继承模式时。书上有这么一个Demo程序:

    <html>
    <head>
    </head>
    <body>
    <script>
    	function SuperType(name){
    		this.name = name;
    	}
    	SuperType.prototype.sayName = function(){
    		alert(this.name);
    	};
    	function SubType(name, age){
    		SuperType.call(this, name);
    		this.age = age;
    	}
    	SubType.prototype = new SuperType();//SuperType.prototype;
    	SubType.prototype.sayAge = function(){
    		alert(this.age);
    	};
    	var instance1 = new SubType("Nicholas", 29);
    	instance1.sayName();
    	instance1.sayAge();
    	
    	//var instance2 = new SuperType("Greg", 27);
    	//instance2.sayAge();
    </script>
    </body>
    </html>

    当中的SubType.prototype = new SuperType()让我产生了疑问。这个语句的目的不就是要让子类型的原型指向父类型的原型实例吗?为什么不直接写出SubType.prototype = SuperType.prototype呢?

    为何非要new一个出来?

    细致考虑之后。我把Demo做了例如以下的改动。弄清楚了这么做的理由何在:

    <html>
    <head>
    </head>
    <body>
    <script>
    	function SuperType(name){
    		this.name = name;
    	}
    	SuperType.prototype.sayName = function(){
    		alert(this.name);
    	};
    	function SubType(name, age){
    		SuperType.call(this, name);
    		this.age = age;
    	}
    	SubType.prototype = SuperType.prototype;
    	SubType.prototype.sayAge = function(){
    		alert(this.age);
    	};
    	var instance1 = new SubType("Nicholas", 29);
    	instance1.sayName();
    	instance1.sayAge();
    	
    	var instance2 = new SuperType("Greg", 27);
    	instance2.sayAge();
    </script>
    </body>
    </html>

    执行以后会发现instance2.sayAge弹出的提示是undefined,也就是说我们在为子类型的加入一个子类型想要持有的方法sayAge时。不小心也污染了父类型,使得父类型也相同拥有了sayAge方法。而父类型根本不具有age属性。当然就会提示这个属性undefined了,这些奇怪现象出现的原因就是直接使用了SubType.prototype = SuperType.prototype造成的。

    假设你把这句换成SubType.prototype = new SuperType()的话再去调用sayAge方法就会执行出错。由于父类型这时候并没有这种方法(没有被子类型污染)。所以说使用new是很科学合理的。

  • 相关阅读:
    读书日记-策略模式
    五、@property的参数
    三、Object-C内存管理
    二、OC的构造方法和descriprtion方法
    一、初始Object-C
    linux中安装eclipse--CnetOS6.5
    linux中安装和配置 jdk
    linux中安装mysql
    bzip2压缩 解压缩
    gzip压缩解压缩
  • 原文地址:https://www.cnblogs.com/mqxnongmin/p/10541100.html
Copyright © 2020-2023  润新知