【问题标题】:Javascript prototype inheritance classesJavascript原型继承类
【发布时间】:2015-11-26 09:19:14
【问题描述】:
      <html>
      <body>
      <script>    
      function animal(kane){
      this.kane:"aaaaa";
      }
      function Rabbit(name) {
      this.name = name;
      } 
      Rabbit.prototype.__proto__=animal.prototype;
      var a=new animal("aaaa");// this wont work when i put a alert box
      var rabbit = new Rabbit('John');
      alert( rabbit.kane );// i should get aaaa but i am getting undefined
     </script>
     </body>
     </html>

我应该在警告框中得到 aaaa,但我该怎么做 这种情况下的原型继承 何时使用 animal.prototype 以及何时使用 new animal()

【问题讨论】:

  • animal 应该如何处理它所采用的 kane 参数?

标签: javascript prototype prototype-programming


【解决方案1】:
  kane:"aaaaa";

这里的语法不正确,应该是this.kane = "aaaaa";

现在对于Rabbit 实例获取属性kane,您可以像使用构造函数窃取一样

 function Rabbit(name) {
     animal.call(this); // constructor stealing
      this.name = name;
 } 

另一种方法是

var a=new animal("aaaa");
var rabbit  = Object.create(a);

在这种方法中,不需要构造函数窃取,因为您直接继承自 animal 的实例

【讨论】:

  • 我做了但是没用仍然无法提醒aaaa
  • 谢谢!我的 Adob​​e 括号有一些问题
  • 如果您将 Child 的原型设置为 Parent 的实例,则通常表明对原型是什么缺乏了解。正确答案应该是:Rabbit.prototype = Object.create(animal.prototype) 假设 animal 是构造函数而不是对象字面量(错误的代码表明它可以双向使用)。如果 animal 是一个对象字面量,那么:'Rabbit.prototype = Object.create(animal)`
  • @DvmSrikantXlador 请参阅我的评论以获得正确的解决方案,有关 JavaScript 原型的信息,您可以阅读以下内容:stackoverflow.com/a/16063711/1641941 如果您真的想学习很多东西并有时间学习,那么目前我认为以下是目前最好的“书”github.com/getify/You-Dont-Know-JS
  • @HMR 我什么时候应该使用 Rabbit.prototype.__proto__=animal.prototype。如果是,动物应该是一门课吗?
猜你喜欢
  • 2010-09-28
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
相关资源
最近更新 更多