我在javascript中有一个"基类",我在下面的例子中称之为"main".我想在我创建的所有子类中使用主类中的一些方法和变量.
我用我目前的想法做了两个例子.我认为后者是首选,因为我将创建一些实例main,并且我听说prototype在有多个实例时这很有用.
我应该使用这两种方法中的任何一种,还是尝试在"类"之间创建继承?如果首选继承,请提供一个示例,因为我不知道如何实现.
var main = (function(){
var out = function() {};
out.staticMethod = function(){
alert('hello world');
};
return out;
})();
var child = (function(main){
var out = function() {};
out.prototype.useMainFunction = function(){
main.staticMethod();
};
return out;
})(main);
var c = new child();
c.useMainFunction();
Run Code Online (Sandbox Code Playgroud)
var main = (function(){
var out = function() {};
out.prototype.publicMethod = function(){
alert('hello world');
};
return out;
})();
var child = (function(main){
var out = function() {};
out.prototype.useMainFunction = function(){
main.publicMethod();
};
return out;
})(new main());
var c = new child();
c.useMainFunction();
Run Code Online (Sandbox Code Playgroud)
我将建议一种不同的方法:
function Main(){
this.message = "Parent";
}
Main.prototype.out = function(){
alert(this.message);
};
function Child(){
this.message = "Child";
};
Child.prototype = new Main();
var child = new Child();
child.out();
var main = new Main();
main.out();
Run Code Online (Sandbox Code Playgroud)
这种方法使用the创建两个类function constructor.第一个类main被赋予一个属性out,该属性被赋予一个函数.第二个类Child将其原型分配给一个新实例Main,在两个类之间创建继承.
工作示例: http ://jsfiddle.net/8QW46/
关于哪种方法最好的问题
我建议使用第一种不使用原型的方法.我建议这样做的原因是你实际上没有使用类(在Javascript类中更好地描述为对象定义).您创建函数的实例.通常使用prototype将函数添加到类的所有实例中.
下面是使用您的方法无法实现的示例,该方法可用于类/对象定义:http://jsfiddle.net/smmb3/