簡體   English   中英

原型的javascript繼承

[英]javascript inheritance by prototype

我正在閱讀本文 ,並以示例為例進行了一些很小的修改

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方法似乎都存在,但是當我調用它時,控制台返回未定義的值,有人可以解釋為什么嗎? 謝謝

方法hello不返回值,因此undefined

您可以將方法更改為如下所示,以返回值:

Parent.prototype.hello = function(){
  return 'hi '+ this.prop2;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM