在Javascript中使用.prototype的原因

Rob*_*und 4 javascript declaration function

使用.prototype而不是在对象本身内声明函数和成员的技术原因是什么.用代码示例解释是最容易的.

使用有什么好处:

RobsObject = function(data){
    this.instanceID = data.instanceID;
    this._formButton = document.getElementById('formSubmit_' + this.instanceID);
    if(this._formButton)
    {
        //set a click listener that
        //points to this._onSubmit, this._onSuccess, and this.onFailure
    }
};

RobsObject.prototype = {
    _onSubmit: function(type, args)
    {
        //make an ajax call
    },

    _onSuccess: function(type, args)
    {
        //display data on the page
    },

    _onFailure: function(type, args)
    {
        //show an alert of some kind
    },
};
Run Code Online (Sandbox Code Playgroud)

反对在Object中声明你的函数,如:

RobsObject = function(data){
    this.instanceID = data.instanceID;
    this._formButton = document.getElementById('formSubmit_' + this.instanceID);
    if(this._formButton)
    {
        //set a click listener that
        //points to this._onSubmit, this._onSuccess, and this.onFailure
    }

    this._onSubmit = function(type, args)
    {
        //make an ajax call
    }

    this._onSuccess = function(type, args)
    {
        //display data on the page
    }

    this._onFailure = function(type, args)
    {
        //show an alert of some kind
    }
};
Run Code Online (Sandbox Code Playgroud)

谢谢.

编辑:正如你们许多人已经指出我在第二个代码片段中的功能应该在他们面前有"这个"才能公开.所以我添加了它.只是我的错误.

Ann*_*lle 14

构造函数中声明prototype的所有内容都由该构造函数的所有实例共享.如果在构造函数中定义函数,那么每个实例都会获得自己的函数副本,这会浪费内存(如果稍后比较两个实例之间的属性,则可能会导致问题).

此外,在您的示例中,构造函数中声明的函数对函数的作用域是私有的.它们不能在实例上作为成员方法调用.为此,您需要将它们分配给对象的属性:

MyObject = functon() {
  // ...

  this.myMethod = function() {
    // ...
  };
}
Run Code Online (Sandbox Code Playgroud)

道格拉斯·克罗克福德(Douglas Crockford)对原型继承进行了很好的描述,这绝对值得一试: JavaScript中的原型继承.

更新:简要原型摘要

使用构造函数创建新对象时,函数prototype属性的值将被指定为新对象的原型对象.(是的,这些名字令人困惑!)这就像在基于类的语言中指定一个超类一样(但不完全!阅读Crockford的页面!)

// MyObject constructor function:
MyObject = function() {
  this.a = 1;
}

// Define an object to use as a prototype.
var thePrototype = { b: 2 };

// Assign thePrototype as the prototype object for new instances of MyObject.
MyObject.prototype = thePrototype;

// Create an instance of MyObject.
var x = new MyObject();
// Everything in thePrototype is available to x.
console.log(x.b);

// x's prototype is a reference to thePrototype, so updating it affects x.
thePrototype.c = 3;
console.log(x.c);

// Setting properties on x always sets them *on x*, even if the property is
//  defined on the prototype:
x.b = 0;
y = new MyObject();
console.log(x.b);
console.log(y.b);
Run Code Online (Sandbox Code Playgroud)