1
我讀這個article,我就拿例子,提出了一些非常小的修改Javascript繼承由原型
function Parent(p1, p2) {
console.log('run here');
var prop1 = p1; // private property
this.prop2 = p2; // public property
// private method
function meth1() { return prop1; }
// public methods
this.meth2 = function(){ return this.prop2; };
this.meth6 = function(){ return meth1(); };
}
Parent.prototype.hello=function(){console.log('hi '+this.prop2);};
function Child(p1, p2, p3, p4) {
Parent.apply(this, arguments); // initialize Parent's members
this.prop3 = p3;
this.meth3 = function(){ return this.prop3; }; // override
var prop4 = p4;
this.meth4 = function(){ return prop4; };
}
Child.prototype = new Parent(); // set up inheritance relation
// console.log(Child.prototype)
var cc = new Child("one", "two", "three", "four");
console.log(cc)
var result1 = cc.meth6(); // parent property via child
var result2 = cc.meth2(); // parent method via child
var result3 = cc.meth3(); // child method overrides parent method
var result4 = cc.hello();
console.log(result1,result2,result3,result4);
的問題是,即使cc.hello方法似乎是存在的,但是當我打電話吧,控制檯返回undefined,有人可以解釋爲什麼嗎?感謝
的'hello'方法沒有按」 t返回任何東西,因此'undefined'。不知道你期望什麼... – elclanrs