Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript原型继承_Javascript - Fatal编程技术网

javascript原型继承

javascript原型继承,javascript,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.

我正在读这篇文章,我举了一个例子,做了一些非常小的修改

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没有返回值,因此它是未定义的

您可以将方法更改为类似以下内容以返回值:

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

hello方法不返回任何内容,因此未定义。不知道你期望什么…哈哈哈,谢谢,我想我的大脑短路了:P