运行Javascript继承代码时出错

Error while running Javascript inheritance code

本文关键字:出错 代码 继承 Javascript 运行      更新时间:2024-04-19

我试图运行此代码来理解Javascript继承,但得到了一个错误

错误:

SyntaxError: Using //@ to indicate source map URL pragmas is deprecated. Use //# instead
http://code.jquery.com/jquery-1.10.1.min.js
Line 1
TypeError: Class.extend is not a function
file:///home/prem/prototype/first.html
Line 13

html文件代码:

    var Person = Class.extend({
      init: function(isDancing){
        this.dancing = isDancing;
      },
      dance: function(){
        return this.dancing;
      }
    });
    var Ninja = Person.extend({
      init: function(){
        this._super( false );
      },
      dance: function(){
        // Call the inherited version of dance()
        return this._super();
      },
      swingSword: function(){
        return true;
      }
    });
    var p = new Person(true);
    p.dance(); // => true
    var n = new Ninja();
    n.dance(); // => false
    n.swingSword(); // => true
    // Should all be true
    p instanceof Person && p instanceof Class &&
    n instanceof Ninja && n instanceof Person && n instanceof Class


</script>
</head>
<body>
</body>

</html>

Javascript继承与您可能使用的其他OOP语言不同,因为它是一种基于原型的语言。MDN有一个很好的小介绍,说明为什么它与Java或C++不同。

我认为你的困惑是基于这样一个事实,即当你把一个对象的设计建立在另一个对象设计的基础上时,js本身没有使用关键字"extend"。然而,有几个js库模仿了设计模式,甚至借用了大多数人熟悉的术语"extend"。

至于您的错误Class.extend is not a function:从技术上讲,"class"是js中的一个保留词,但我认为它迄今为止没有任何作用。因此,除非您或其他人声明了一个名为"Class"的对象,并为其提供了一个称为"extend"的函数属性,否则当您尝试调用它时,js引擎不知道该怎么办