English 中文(简体)
Java文中原型或标本所附方法有什么区别?
原标题:What is difference between method attached to prototype or object instance in Javascript?

我对 Java版原型的使用感到困惑不解。

举以下例子:

(1)

   function Rectangle(w, h) { 
      this.width=w; 
      this.height=h; 
      this.area=function() { this.width * this.height; }
   }

And a similar case where the area is attached to a prototype as follows:

(2)

   function Rectangle(w, h) { 
      this.width=w; 
      this.height=h; 
   }
   Rectangle.prototype.area=function() { this.width * this.height; }
  • What is the diffrence between (1) and (2) ?
  • When would you use (1) or (2) for writing methods on classes?
最佳回答

prototypes are best shown differently.

function rectangle(w, h) {
    var rect = {};
    rect.width=w; 
    rect.height=h; 
    rect.area=function() { return this.width * this.height; };
    return rect;
}

vs

var Rectangle = {
    area: function() { return this.width * this.height; }
}

function rectangle(w, h) {
    var rect = Object.create(Rectangle);
    rect.width=w; 
    rect.height=h; 
    return rect;
}

这一概念很简单,你把共同点放在原型上,然后继承。

你们何时想要使用原型? 途径。

当然,你可能希望。 改善ES5 OO 食糖

问题回答

暂无回答




相关问题
UserControl constructor with parameters in C#

Call me crazy, but I m the type of guy that likes constructors with parameters (if needed), as opposed to a constructor with no parameters followed by setting properties. My thought process: if the ...

Strange "type class::method() : stuff " syntax C++

While reading some stuff on the pImpl idiom I found something like this: MyClass::MyClass() : pimpl_( new MyClassImp() ) First: What does it mean? Second: What is the syntax? Sorry for being such ...

Anonymous class question

I ve a little doubt over this line: An anonymous class cannot define a constructor then, why we can also define an Anonymous class with the following syntax: new class-name ( [ argument-list ] ) {...

Why copy constructor is not called in this case?

Here is the little code snippet: class A { public: A(int value) : value_(value) { cout <<"Regular constructor" <<endl; } A(const A& other) : value_(other....

Invoking an instance method without invoking constructor

Let s say I have the following class which I am not allowed to change: public class C { public C() { CreateSideEffects(); } public void M() { DoSomethingUseful(); } } and I have to call M ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

热门标签