javascript继承原型

时间:2015-08-13 22:15:03

标签: javascript

我正在读这个article,我拿了这个例子做了一些非常小的修改

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,有人可以解释一下原因吗?谢谢

1 个答案:

答案 0 :(得分:1)

方法hello没有返回值,因此它是undefined

您可以将方法更改为此类型以返回值:

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