function ClassA(sColor)
{
this.color = sColor;
this.sayColor = function() {
alert(this.color);
}
}
function ClassB(sColor)
{
this.newMethod = ClassA; //什么意思
this.newMethod(sColor); //这样写下为什么就得到了ClassA定义的属性和方法
delete this.newMethod; //为什么要删除
}
请写出详细的理解
{
this.color = sColor;
this.sayColor = function() {
alert(this.color);
}
}
function ClassB(sColor)
{
this.newMethod = ClassA; //什么意思
this.newMethod(sColor); //这样写下为什么就得到了ClassA定义的属性和方法
delete this.newMethod; //为什么要删除
}
请写出详细的理解
this.newMethod = ClassA;
this.newMethod(sColor); //这就相当与在对象自己身上调用ClassA函数,ClassA的this指向了ClassB
//相当与 ClassA.call(this);
delete this.newMethod; //用完就删除,如果是 ClassA.call(this)就不用删除了
function ClassB(sColor)//把此函数看作构造函数
{
this.newMethod = ClassA; //字面意思,定义成员方法,把函数ClassA作为成员方法
this.newMethod(sColor); //执行成员方法,成员方法里面this指代类的实例,该方法给该实例添加了color,sayColor两个成员,不是你想的得到了ClassA的成员
delete this.newMethod; //此方法已经执行,删不删都一样,不影响属性的添加,区别只在构造出的对象中是否存在该方法,如果不删除,还可以在实例中调用该方法,修改那两个成员的值
}下面的写法能有同样效果,可以帮助你理解:
function ClassB(sColor)//把此函数看作构造函数
{
this.newMethod = ClassA; //字面意思,定义成员方法,把函数ClassA作为成员方法
}
var objB=new ClassB();
objB.newMethod("red");//在对象中调用该方法,同样可以给对象添加那两个成员,原写法在构造函数中调用只是调用时间的区别,实质是相同的,能理解么?
alert(objB.color);