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

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

本文关键字:添加 方法 prototype 什么 区别 JavaScript 构造函数      更新时间:2023-09-26

我使用的是John Resig的JavaScript类定义样式。下面是一个示例类。

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

定义舞蹈方法的另一种方法是:

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

我喜欢使用第一种方法,但有人建议我使用效率低。这两种方式有什么区别?

我自己刚刚找到解决方案。

John Resig的扩展函数会根据作为参数传递的对象自动创建一个构造函数。在第一种方式中,对象中的舞蹈方法将自动分配给返回对象的原型。这意味着返回的构造函数(类)实际上将使用第二种样式。所以没有必要使用第二种方式。

因此,当使用John Resig的代码时,第一种方法并不是低效的。