我想创建一个类的模型,比如说
var car = function(){
var color;
this.setColor = function(clr){
color = clr;
}
}
现在我想要更多的类,例如 volvo()
。但我也想要 car()
拥有的所有东西,在 volvo()
中使用它,就像这样
var volvo = function(){
...probably some code here
this.getColor = function(){
return color;
}
}
我该怎么做?
最佳答案
您想要实现的目标称为继承,并且由于 JavaScript 不像 Java、C# 和其他语言那样基于类,而是基于原型(prototype),因此实现起来并不容易。
实现它的方法有很多:
一种方法是使用框架,例如 Backbone.js , AngularJS或Ember.js 。然后在您的模型类中,基本上您可以使用 Extend
关键字,然后立即获得继承。
另一种方法是将 John Resig(jQuery 创建者)编写的以下代码包含到您的应用程序中:
/* 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;
};
})();
加载此代码后,您将能够使用它来解决您的问题:
var Car = Class.Extend({
setColor: function(clr){
color = clr;
}
});
var volvo = Car.Extend({
getColor: function () {
return color;
}
});
在 JavaScript Inheritance by John Resig 中阅读相关内容邮政。祝你好运!
关于javascript - 如何创建函数模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532218/