JavaScript大牛们,路过请进。有2个JS很核心的问题要提问下。
JavaScript大牛们,路过请进。有2个JS很核心的问题要提问下。
?
1.请问constructor1.prototype = constructor2.prototype和constructor1.prototype = new constructor2() 的区别
【备注】constructor1和constructor2分别指2个我自己创建的构造函数。如下:
????????????function Person(){ /*coding...*/}
????????????function Man(){ /*coding*/}
????????????Man.prototype = Person.prototype和Man.prototype = new Person()的区别?
?
2.请问JavaScript中子类继承父类时,是将父类里面的方法定义实实在在的拷贝到自己的类定义中吗?我的意思就是问,比如上面的Person中定义了一个公有的方法(可以被继承),那么Man继承了Person后,在Man的类定义中有Person中那个公有方法的定义还是只是一个方法的引用呢???
?
这2个问题困恼了我很久,请神人们赐教。
?
?
?
?
?
2 楼 bantouyan 2011-04-05 第一个问题:Man.prototype = Person.prototype的含义是类Man与类Person共用同一个原型对象,他们有相同的原型属性,请验证下面的代码:
Man.prototype = Person.prototype;
var m = new Man();
var p = new Person();
alert(m instanceof Man); //true
alert(m instanceof Person); //true
alert(p instanceof Man); //true
alert(p instanceof Person); //true
可以说Man与Person是同一个类,修改Man的prototype会影响到Person,反之亦然。唯一不同的是用new Man()创建的对象与用new Person()创建的对象可能会有不同的实例属性。
Man.prototype = new Person()是标准的原型继承方式,Man是Person的子类,拥有Person的一切属性,而且修改Man的prototype不会影响Person,但修改Person的prototype会影响到Man,可以测验下面的代码:
Man.prototype = new Person();
var m = new Man();
var p = new Person();
alert(m instanceof Man); //true
alert(m instanceof Person); //true
alert(p instanceof Man); //false
alert(p instanceof Person); //true
第二个问题:
JavaScript中类的所有方法都是对象,类的方法只是对方法对象的一个引用,无论在类Man中还是在Person中,所有的方法都是引用。