为什么警报在javascript + jquery中给出undefined

时间:2015-05-09 07:08:24

标签: javascript jquery

我正在尝试在javascript中制作inhertance类示例。但我在警告中未定义。但我认为它应该在警报

中提供“naveen”
function a (){
          this.name="naveen"
      }
      a.prototype.getname=function(){
          return  "Do :"+ this.name;
      }
          b.prototype= a.prototype;
          function b(){
          }
          alert(new b().name)
      alert(new b().getname())

小提琴 http://jsfiddle.net/zhvsafaj/

编辑

function a (){
          this.name="naveen"
          throw  new Error('cannot create intance')
      }
      a.prototype.getname=function(){
          return  "Do :"+ this.name;
      }
          b.prototype= new a();
          function b(){
          }
          alert(new b().name)
      alert(new b().getname())

2 个答案:

答案 0 :(得分:2)

您的代码存在的问题是,在fgets()实例的情况下,您永远不会设置实例属性.card{ border:1px solid black; height:120px; width:100%; position:absolute; bottom: 0; -webkit-border-top-left-radius: 10px; -webkit-border-top-right-radius: 10px; -moz-border-radius-topleft: 10px; -moz-border-radius-topright: 10px; border-top-left-radius: 10px; border-top-right-radius: 10px; } #wrap{ overflow:hidden; position:absolute; bottom:0; left: 0; width: 100%; height: 120px !important; } #card1{ background:black; top:0; color:white; } 。它是在name构造函数中分配的,但不是b。请注意,a是自己的属性,它不属于b,因此不会被name实例共享。

如果您希望a.prototype的实例拥有属性b,则需要使用b来设置它。另请注意,共享name等原始属性没有多大意义,原型模式的真正好处在于共享方法。

答案 1 :(得分:1)

创建类

的对象实例
b.prototype= new a();

所以你的代码是

function a (){
          this.name="naveen"
      }

      a.prototype.getname=function(){
          return  "Do :"+ this.name;
      }
      b.prototype = new a();
          function b(){
          }
      alert(new b().name)
      alert(new b().getname())

Fiddle