【问题标题】:What does "the prototype belongs to the class not the instance" mean in javascript?javascript中的“原型属于类而不是实例”是什么意思?
【发布时间】:2011-05-27 10:02:44
【问题描述】:

我问了这个问题:

Why cant I declare a constructor instantiate an object and then access the prototype?

你可以看到我已经标记了答案。我理解回复,但我对他的意思有点困惑:

The prototype belongs to the class, not the instance:

这是否意味着javascript在这个例子中有一个类?我认为javascript是无类的?它只有函数构造函数......函数构造函数在什么时候成为一个类?是当您使用 .prototype 访问器向其中添加其他成员时?

【问题讨论】:

    标签: javascript prototype-programming


    【解决方案1】:

    实际上class 是一个OOP 术语,并不是真正的javascript。意思是原型属于constructor。所以在

    function MyConstructor(prop){
       this.foo = prop || 'foo';
    }
    MyConstructor.prototype.bar = 'allways bar';
    var mc1 = new MyConstructor('I am mc1'), 
        mc2 = new MyConstructor('I am mc2');
    
    alert(mc1.bar) ; //=> allways bar
    alert(mc2.bar) ; //=> allways bar
    alert(mc1.foo) ; //=> I am mc1
    alert(mc2.foo) ; //=> I am mc2
    

    bar 属于构造函数 (MyConstructor) 原型。对于每个实例,它始终是“总是吧”。 foo 是一个实例属性(默认值为 'foo'),可以为每个实例分配不同的值。

    【讨论】:

    • 嗨,请问'this.foo = prop || '富';'方法?那是 OR 符号吗?
    • 嗨 Pete2k,是的,是一个 OR 符号。它的简写是:如果prop 的计算结果为未定义(或空),则将值'foo' 分配给this.prop。它通常用于确保某些变量获得(默认)值。
    【解决方案2】:

    JavaScript 的原型是一个与类非常相似但又不完全相同的概念。阅读下面的文章,它提供了互联网上关于此问题的最佳解释之一。

    http://www.crockford.com/javascript/inheritance.html

    【讨论】:

      【解决方案3】:

      javascript 中没有类。

      构造函数是函数,并具有引用对象的 prototype 属性。您可以向该对象添加函数,或将新对象分配给原型属性以创建继承链:

      function MyConstructor () {
        // initialise instance
      }
      
      MyConstructor.prototype.someMethod = function() {
          // ...
        };
      
      MyConstructor.prototype.anotherMethod = function() {
          // ...
      };
      

      或者用另一个构造函数的实例替换它:

      MyConstructor.prototype = new SomeOtherConstructor();
      
      MyConstructor.prototype.constructor = MyConstructor;
      

      等等。现在,当创建 MyConstructor 的实例时:

      var anInstance = new MyConstructor();
      

      构造函数返回的对象具有 MyConstructor.prototype 作为其内部 [[prototype]] 属性并“继承”其方法和属性(以及其整个 [[prototype]] 链上的方法和属性) .

      所以 MyConstructor 的每个实例在其原型链上都有其 MyConstructor.prototype。但是请注意,MyConstructor 并不继承自它自己的原型,它仅由 new MyConstructor 创建的实例使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-11
        • 2017-12-06
        • 1970-01-01
        • 2013-11-02
        • 2016-07-27
        • 2010-10-23
        • 2012-08-15
        • 1970-01-01
        相关资源
        最近更新 更多