这几天看到了Javascript采用冒充法继承,代码如下:
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 objB = new classB("blue", "name");
objB.sayColor();//blue
objB.sayName();//name 我要提的一个问题是:为什么在ClassB类继承了ClassA之后必须要用 delete this.newMethod;这一句,虽然注释已经说有了它的作用,但是我自己试了一下,如果不用也不会产生什么后果,请高手们能够解释,最好是举例说明?
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 objB = new classB("blue", "name");
objB.sayColor();//blue
objB.sayName();//name 我要提的一个问题是:为什么在ClassB类继承了ClassA之后必须要用 delete this.newMethod;这一句,虽然注释已经说有了它的作用,但是我自己试了一下,如果不用也不会产生什么后果,请高手们能够解释,最好是举例说明?
不然以后classB的默写涉及到newMethod属性的操作可能会影响到classA
this.newMethod = classA; 函数名只是指向它的指针,这里this.newMethod也就是相当于一个指针指向了classA这个构造函数,不删除的话就可以通过这个指针修改classA里面的属性和方法。
function classB(sColor, sName) {
var a= this.newMethod = classA;
var b= this.newMethod(sColor);
alert(a==b)
delete this.newMethod;
alert(typeof a)
alert(typeof b)
this.name = sName;
this.sayName = function () {
alert(this.name);
};
} 看看这个 应该明白了
有空看看这个帖子http://tech.idv2.com/2008/01/09/javascript-variables-and-delete-operator/