新手问prototype
function ClassA(sColor) {
this.name = "dddd";
}
function ClassB(sColor, sName) {
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function () {
alert(this.name);
};
var objB = new ClassB("blue", "Nicholas");
objB.sayName();
delete objB.sayName;
objB.sayName();
问:
ClassB.prototype.sayName 这个sayName方法是加在classb对象上了还是classa对象上了,如果加在classb上,为什么用delete删除后还能输出?如果加在classa上,为什么this指向classb的name而不是classa的name??
[解决办法]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title> new document </title> <meta name="generator" content="editplus" /> <meta name="author" content="Gao YiXiang" /> <meta name="email" content="yixianggao@126.com" /> <meta name="keywords" content="javascript dhtml dom" /> <meta name="description" content="I love web development." /></head><body> <script type="text/javascript"> <!--function ClassA(sColor){ this.name = "dddd";}function ClassB(sColor, sName){ this.name = sName; this.color = sColor;}ClassB.prototype = new ClassA();ClassB.prototype.sayName = function () { alert(this.name);};var objB = new ClassB("blue", "Nicholas");objB.sayName(); // sayName 当然是 ClassB 上的!delete objB.sayName; // 这样仅删除了当前实例对 ClassB.prototype.sayName 的引用。//delete ClassB.prototype.sayName; // 这样才真地删除了!objB.sayName(); // 由于原型方法仍然可用,因此调用 ClassB.prototype.sayName 成功! //--> </script></body></html>
[解决办法]
楼上正解.事实上这个新的方法是加到A里去了。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title> new document </title> <meta name="generator" content="editplus" /> <meta name="author" content="Gao YiXiang" /> <meta name="email" content="yixianggao@126.com" /> <meta name="keywords" content="javascript dhtml dom" /> <meta name="description" content="I love web development." /></head><body> <script type="text/javascript"> <!--function ClassA(sColor){ this.name = "dddd";}function ClassB(sColor, sName){ this.name = sName; this.color = sColor;}objA = new ClassA();ClassB.prototype = objA;ClassB.prototype.sayName = function () { alert(this.name);};var objB = new ClassB("blue", "Nicholas");objB.sayName(); // sayName 当然是 ClassB 上的!objA.sayName();//这里say的就是classb的了。delete objB.sayName; // 这样仅删除了当前实例对 ClassB.prototype.sayName 的引用。//delete ClassB.prototype.sayName; // 这样才真地删除了!//delete objA.sayName; //这样也可以删除.objB.sayName(); // 由于原型方法仍然可用,因此调用 ClassB.prototype.sayName 成功! //--> </script></body></html>