简体   繁体   English

直接向 JavaScript 构造函数添加方法和使用原型添加方法有什么区别?

[英]What is the difference between adding a method to a JavaScript constructor directly and adding a method using prototype?

I am using John Resig's JavaScript class definition style .我正在使用 John Resig 的 JavaScript class 定义样式 Below is an example class.下面是一个示例 class。

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});

An alternative way to define the dance method would be:定义 dance 方法的另一种方法是:

Person.prototype.dance = function(){
   return this.dancing;
};

I like using the first way but someone suggested me that it is inefficient.我喜欢使用第一种方式,但有人建议我这样做效率低下。 What is the difference between the two ways?这两种方式有什么区别?

Just found out the solution myself.刚刚自己找到了解决方案。

John Resig's extend function automatically creates a constructor from the object passed as an argument. John Resig 的扩展 function 自动从作为参数传递的 object 创建一个构造函数。 In the first way, the dance method in the object would automatically be assigned to the prototype of the returned object.在第一种方式中,object 中的 dance 方法将自动分配给返回的 object 的原型。 It means the returned constructor (class) would be in fact using the 2nd style.这意味着返回的构造函数(类)实际上将使用第二种样式。 So it is unnecessary to use the 2nd way.所以没有必要使用第二种方式。

Thus when using John Resig's code the first way is NOT inefficient.因此,当使用 John Resig 的代码时,第一种方法并不是低效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM