在JavaScript中实现简单继承

时间:2015-01-15 09:41:30

标签: javascript php prototypal-inheritance

我一直在我的网络应用中使用John Resig javascript class implementation,但测试显示它真的很慢。我发现它对于扩展对象的方式非常有用,并且从拥有更好的代码和更少的冗余中获得了好处。

在一些帖子中解释说,由于_super方法的处理方式很慢。 由于super是Java风格,并且大部分时间我都是用PHP开发的,因此我使用parent::样式(在PHP中使用)创建了我自己的Resig实现版本,目的是使其更快。这是:

(function () {
  this.Class = function () {
  };
  Class.extend = function extend(prop) {
    var prototype = new this();
    prototype.parent = this.prototype;

    for (var name in prop) {
      prototype[name] = prop[name];
    }

    function Class() {
      this.construct.apply(this, arguments);
    }
    Class.prototype = prototype;
    Class.prototype.constructor = Class;
    Class.extend = extend;

    return Class;
  };
}) ();

使用案例:

var Person = Class.extend({
  construct: function (name) {
    this.name = name;

  },
  say: function () {
    console.log('I am person: '+this.name);
  },

});

var Student = Person.extend({
  construct: function (name, mark) {
    this.parent.construct.call(this, name);
    this.mark = 5;
  },
  say: function () {
    this.parent.say();

    console.log('And a student');
  },
  getMark: function(){
   console.log(this.mark);
  }
});

var me = new Student('Alban');
me.say();
me.getMark();
console.log(me instanceof Person);
console.log(me instanceof Student);

对此有何看法?我这么快?那么正确性呢?

1 个答案:

答案 0 :(得分:-1)

初看起来,这看起来不错:),但我认为coffeescript所做的实现目前是最复杂的实现之一:

class Person
  walk: ->
    return

class myPerson extends Person
  constructor: ->
    super

转换为:

var Person, myPerson,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Person = (function() {
  function Person() {}

  Person.prototype.walk = function() {};

  return Person;

})();

myPerson = (function(_super) {
  __extends(myPerson, _super);

  function myPerson() {
    myPerson.__super__.constructor.apply(this, arguments);
  }

  return myPerson;

})(Person);

它快速,干净并且可以进行自己的属性检查。