在Javascript中附加到原型或对象实例的方法有什么区别? [英] What is difference between method attached to prototype or object instance in Javascript?

查看:170
本文介绍了在Javascript中附加到原型或对象实例的方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Javascript中原型的使用有点困惑。



让我们看下面的例子:



(1)

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

以及类似的情况,其中区域附加到原型如下:



(2)

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




  • (1)和(2)之间的差异是什么?

  • 何时使用(1)或(2)来写类方法?


解决方案
 函数矩形(w,h){
var rect = { };
rect.width = w; $ b $ c 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


I am a bit confused about the usage of prototypes in Javascript.

Let's take the following example:

(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;
}

The idea is simple, you put common stuff on a prototype object and you then inherit from it.

As for when you want to use the prototype? Always.

Of course you probably want to Improve ES5 OO with sugar

这篇关于在Javascript中附加到原型或对象实例的方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆