2

根据 Douglas Crockford 的说法,我可以使用http://javascript.crockford.com/prototypal.html之类的东西(稍作调整)......但我对 jQuery 的处理方式很感兴趣。使用 $.extend 是一种好习惯吗?

我有 4 节课:

            var A = function(){ } 
            A.prototype = {
                name : "A",
                cl : function(){
                    alert(this.name);
                }
            }
            var D = function(){} 
            D.prototype = {
                say : function(){
                    alert("D");
                }
            }

            var B = function(){} //inherits from A
            B.prototype = $.extend(new A(), {
                name : "B"
            });

            var C = function(){} //inherits from B and D
            C.prototype = $.extend(new B(), new D(), {
                name : "C"
            });


            var o = new C();

            alert((o instanceof B) && (o instanceof A) && (o instanceof C)); //is instance of A, B and C 
            alert(o instanceof D); //but is not instance of D

所以,我可以从 A、B、C 和 D 中调用每个方法、属性...。问题来了,当我想测试 o 是否是 D 的实例时?我该如何克服这个问题?

4

2 回答 2

4

使用 $.extend 是一种好习惯吗

$.extend对于单例很有用,但对于原型并不理想。

使用Object.create(或 Crockford 的 polyfill),您可以轻松地创建这样的类。我$.extend用来简单地处理属性并为它们提供默认值和模块模式以使其井井有条。希望这可以帮助:

// Helper that makes inheritance work using 'Object.create'
Function.prototype.inherits = function(parent) {
  this.prototype = Object.create(parent.prototype);
};

var Person = (function PersonClass() {

  var _defaults = {
    name: 'unnamed',
    age: 0
  };

  function Person(props) {
    $.extend(this, props, _defaults);
  }

  Person.prototype = {
    say: function() {
      return 'My name is '+ this.name;
    }
  };

  return Person;

}());

var Student = (function StudentClass(_super) {

  Student.inherits(_super); // inherit prototype

  var _defaults = {
    grade: 'untested'
  };

  function Student(props) {
    _super.apply(this, arguments); // call parent class
    $.extend(this, props, _defaults);
  }

  Student.prototype.say = function() {
    return 'My grade is '+ this.grade;
  };

  return Student;

}(Person));

var james = new Student({ name: 'James', grade: 5 });

console.log(james instanceof Student); // true
console.log(james instanceof Person); // true
于 2013-03-11T15:22:58.680 回答
1

An object has only one prototype, so you cannot make it an instance of two other types with one call.

$.extend(new B(), new D(), ... creates an object that is an instance of B. Then all properties of D are copied to the newly created object. But the object will still be an instance of B.

Using $.extend is neither good nor bad per se. But you are bound to jQuery, which makes your code less reusable. And you have to be aware of the fact that $.extend overwrites properties with the same name, which might or might not be what you want.

于 2013-03-11T16:01:07.873 回答