JavaScript:.extend和.prototype用于什么?

And*_*rew 119 javascript prototype object-model

我是一个相对较新的JavaScript,并继续在我正在使用的第三方库中看到.extend和.prototype.我认为它与Prototype javascript库有关,但我开始认为情况并非如此.这些用于什么?

med*_*iev 131

Javascript的继承是基于原型的,因此您可以扩展对象的原型,例如Date,Math,甚至是您自己的自定义对象.

Date.prototype.lol = function() {
 alert('hi');
};

( new Date ).lol() // alert message
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我为所有 Date对象(已经存在的对象和所有新对象)定义了一个方法.

extend 通常是一个高级函数,它复制您想要从基类扩展的新子类的原型.

所以你可以这样做:

extend( Fighter, Human )
Run Code Online (Sandbox Code Playgroud)

并且Fighter构造函数/对象将继承原型Human,因此如果您定义诸如live和之类的方法die,Human那么Fighter也将继承那些.

更新澄清:

"高级函数"意味着.extend不是内置的,但通常由jQuery或Prototype等库提供.

  • "高级函数"意味着`.extend`不是内置的,但通常由jQuery或Prototype等库提供. (75认同)
  • 我想补充一点,不建议在JS中扩展原生对象的原型 (13认同)
  • 在现代Javascript编程中,习惯上将全局和本机对象视为公共浴室的元素; 你不能避免去那里,但你应该尽量减少与表面的接触.这是因为`更改本机对象可能会破坏其他开发人员对这些对象的假设,导致javascript错误,这些错误通常需要花费数小时来跟踪.这个答案的主要句子似乎歪曲了这个有价值的JavaScript实践. (8认同)

pno*_*los 24

.extend()由许多第三方库添加,以便于从其他对象创建对象.有关示例,请参阅http://api.jquery.com/jQuery.extend/http://www.prototypejs.org/api/object/extend.

.prototype 指的是一个对象的"模板"(如果你想称它),所以通过向对象的原型添加方法(你在库中看到很多东西,以添加到String,Date,Math,甚至Function)这些方法被添加到该对象的每个新实例.


CMS*_*CMS 18

extend例如,jQueryPrototypeJS中的方法将所有属性从源复制到目标对象.

现在关于prototype属性,它是函数对象的成员,它是语言核心的一部分.

任何函数都可以用作构造函数,以创建新的对象实例.所有功能都具有此prototype属性.

new函数对象上使用运算符时,将创建一个新对象,它将从其构造函数继承prototype.

例如:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
Run Code Online (Sandbox Code Playgroud)


amb*_*odi 18

Javascript继承似乎就像一场无处不在的公开辩论.它可以被称为"Javascript语言的奇怪案例".

我们的想法是有一个基类,然后扩展基类以获得类似继承的功能(不完全,但仍然).

整个想法是获得原型的真正含义.直到我看到John Resig的代码(接近于什么jQuery.extend)编写了一个代码块并且他声称base2和原型库是灵感的来源之后我才得到它.

这是代码.

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */  
     // Inspired by base2 and Prototype
    (function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();
Run Code Online (Sandbox Code Playgroud)

有三个部分正在完成这项工作.首先,遍历属性并将它们添加到实例中.之后,您将创建一个构造函数,以便稍后添加到对象中.现在,关键行是:

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
Run Code Online (Sandbox Code Playgroud)

您首先指向Class.prototype所需的原型.现在,整个对象已经改变了意味着您需要强制布局回到自己的布局.

用法示例:

var Car = Class.Extend({
  setColor: function(clr){
    color = clr;
  }
});

var volvo = Car.Extend({
   getColor: function () {
      return color;
   }
});
Run Code Online (Sandbox Code Playgroud)

通过John Resig的帖子在Javascript继承中阅读更多相关信息.