24

2 つのクラスを作成する簡単な方法を探しています。一方は他方から継承し、子は親のメソッドの 1 つを再定義し、新しいメソッド内で親のメソッドを呼び出します。

たとえば、クラスAnimalandDogがあり、Animal クラスはmakeSound()音を出力する方法を確立するメソッドを定義し、Dog はそれを独自のmakeSound()メソッドでオーバーライドして「横糸」の音を出しますがmakeSound()、その横糸を出力するために Animal も呼び出します。

ここで John Resig のモデルを見ましたが、ECMA スクリプト 5 で明らかに減価償却されているネイティブarguments.calleeプロパティを使用しています。それは、John Resig のコードを使用すべきではないということですか?

Javascript のプロトタイプ継承モデルを使用して、動物/犬のコードを書くためのきちんとした簡単な方法は何でしょうか?

4

4 に答える 4

27

それは、ジョン・レシグのコードを使用すべきではないという意味ですか?

正解です。厳密モードでES5を使用している場合ではありません。ただし、簡単に適応させることができます。

/* Simple JavaScript Inheritance for ES 5.1
 * based on http://ejohn.org/blog/simple-javascript-inheritance/
 *  (inspired by base2 and Prototype)
 * MIT Licensed.
 */
(function(global) {
  "use strict";
  var fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  function BaseClass(){}

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

    // Set up the prototype to inherit from the base class
    // (but without running the init constructor)
    var proto = Object.create(_super);

    // Copy the properties over onto the new prototype
    for (var name in props) {
      // Check if we're overwriting an existing function
      proto[name] = typeof props[name] === "function" && 
        typeof _super[name] == "function" && fnTest.test(props[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, props[name])
        : props[name];
    }

    // The new constructor
    var newClass = typeof proto.init === "function"
      ? proto.hasOwnProperty("init")
        ? proto.init // All construction is actually done in the init method
        : function SubClass(){ _super.init.apply(this, arguments); }
      : function EmptyClass(){};

    // Populate our constructed prototype object
    newClass.prototype = proto;

    // Enforce the constructor to be what we expect
    proto.constructor = newClass;

    // And make this class extendable
    newClass.extend = BaseClass.extend;

    return newClass;
  };

  // export
  global.Class = BaseClass;
})(this);
于 2013-02-24T13:35:09.520 に答える
7

Object.create() + コンストラクターの割り当てによるプロトタイプ チェーン

function Shape () {
    this.x = 0;
    this.y = 0;
}

Shape.prototype.move = function (x, y) {
    this.x += x;
    this.y += y;
};

function Rectangle () {
    Shape.apply(this, arguments); // super constructor w/ Rectangle configs if any
}

Rectangle.prototype = Object.create(Shape.prototype); // inherit Shape functionality
// works like Rectangle.prototype = new Shape() but WITHOUT invoking the constructor

Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

rect instanceof Rectangle && rect instanceof Shape // returns true

Object.create ドキュメントから

新しいキーワードに関する情報

于 2015-01-23T07:41:12.230 に答える
3

これは、チェーンを使用した継承と _super の動作を可能にするために私が思いついたものです。

/**
 * JavaScript simple inheritance
 * by Alejandro Gonzalez Sole (base on John Resig's simple inheritance script)
 * MIT Licensed.
 **/
(function (){
    var initializing = false,
      fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.* /;

    function Class(){};

    function inheritClass(superClass){
      var self = this;
      function Class(){
        if (!initializing && typeof this._constructor === 'function')
          this._constructor.apply(this, arguments);
      }

      Class.prototype = superClass.prototype;
      Class.prototype._constructor = superClass;
      Class.prototype.constructor = Class;
      Class.extend = extendClass;
      //currenlty if you inhert multiple classes it breaks
      Class.inherit = inheritClass;
      return Class;
    };

    function extendClass(prop) {
      var self = this;
      var _super = self.prototype;

      function Class(){
        if (!initializing && typeof this._constructor === 'function')
          this._constructor.apply(this, arguments);
      }

      initializing = true;
      var prototype = new self();
      initializing = false;

      for (var name in prop) {
        prototype[name] = typeof prop[name] == "function" &&
          typeof _super[name] == "function" && fnTest.test(prop[name]) ?
          (function(name, fn){
            return function() {
              var tmp = this._super;
              this._super = _super[name];
              var ret = fn.apply(this, arguments);
              this._super = tmp;
              return ret;
            };
          })(name, prop[name]) : prop[name];
      }

      Class.prototype = prototype;
      Class.prototype.constructor = Class;
      Class.extend = extendClass;
      Class.inherit = inheritClass;

      return Class;
    };

    Class.extend = extendClass;
    Class.inherit = inheritClass;

})();


//EXAMPLE

function Person(){
  this.name = "No name";
  console.log("PERSON CLASS CONSTRUCTOR")
}
Person.prototype.myMethod = function (t){
  console.log("MY PERSON", t, this.name);
  return -1;
}

var TestPerson = Class.inherit(Person).extend({
    _constructor: function(){
      this._super();
      this.name = "JOhn";
      console.log("TEST PERSON CONSTRUCTOR");
    },
    myMethod: function (t){
      console.log("TEST PERSON", t, this.name);
      return this._super(t)
    }
});


var test = new TestPerson();

console.log(test.myMethod("BA"));

私はpixiラッパーhttps://github.com/guatedude2/pixijs-cliでテストしてきましたが、これまでのところ非常にうまく機能しています。

このアプローチで私が遭遇した唯一の問題は、一度しか継承できないことです。継承を再度実行すると、以前の継承が上書きされます。

于 2015-03-22T01:34:45.047 に答える
2

私は、 TypeScriptが継承の形式を生成する方法を好みます(ドロップダウンから [単純な継承] を選択します)。それは を使用しませんarguments.calleeが、__extends prototype.

var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();
var Snake = (function (_super) {
    __extends(Snake, _super);
    function Snake(name) {
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);
var Horse = (function (_super) {
    __extends(Horse, _super);
    function Horse(name) {
        _super.call(this, name);
    }
    Horse.prototype.move = function () {
        alert("Galloping...");
        _super.prototype.move.call(this, 45);
    };
    return Horse;
})(Animal);
var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
于 2013-02-24T11:27:08.547 に答える