我正在寻找一种简单的方法来创建两个类,一个类继承另一个类,子类重新定义父类的方法之一,并在新方法中调用父类的方法。
例如,有一个班级Animal
and Dog
,其中 Animal 类定义了一个方法makeSound()
它建立了如何输出声音,然后 Dog 在它自己的中重写makeSound()
方法发出“汪”声,同时也调用 Animal 的makeSound()
输出那个低音。
我看了约翰·雷西格的模型here http://ejohn.org/blog/simple-javascript-inheritance/,但它使用本机arguments.callee
该属性在 ECMA 脚本 5 中显然已贬值。这是否意味着我不应该使用 John Resig 的代码?
使用 Javascript 的原型继承模型编写动物/狗代码的一种简洁、简洁的方法是什么?
这是否意味着我不应该使用 John Resig 的代码?
正确,当你在严格模式下使用 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)