注意:
正如答案所说,问题中提出的代码确实 NOT 真正实现了继承(否则它会成为一个答案而不是一个问题..)由于问题和我的问题中描述的一些问题评论。它可以像 假的 继承一样工作(甚至不是原型)。
摘要
简而言之,使它与我们编写通用OO语言而不是javascript类似,但保持继承是正确的。
故事
Object.create是实现原型继承的好方法,但对于 类型的 大脑和 新>来说,它有点令人困惑em> 粉丝。
我们可以通过各种方式编写javascript代码,就像我们使用伪经典模式编写其他OO语言一样。因为它是伪 - 经典,我们必须正确处理javascript的底层原型继承。
我想要找到的是一种可以在类声明上实现伪经典继承的方法。演示代码放在帖子的后面,按预期工作,然而,有一些烦人的事情:
我无法在类声明中删除return
,否则继承将无效。
除了在类声明中传递this
之外我没办法让返回的闭包知道什么是this
。
我也想摆脱function (instance, _super) {
,但还没有好主意。
不继承类的 static (自己的属性)。
解决方案比现有框架更多的是一些语法糖,一个好的模式是适用的。
_extends
功能:
function _extends(baseType) {
return function (definition) {
var caller=arguments.callee.caller;
var instance=this;
if(!(instance instanceof baseType)) {
(caller.prototype=new baseType()).constructor=caller;
instance=new caller();
}
var _super=function () {
baseType.apply(instance, arguments);
};
definition(instance, _super);
return instance;
};
}
Abc
类:
function Abc(key, value) {
return _extends(Object).call(this, function (instance, _super) {
instance.What=function () {
alert('What');
};
instance.getValue=function () {
return 333+Number(value);
};
instance.Value=instance.getValue();
instance.Key=key;
});
}
Xyz
类:
function Xyz(key, value) {
return _extends(Abc).call(this, function (instance, _super) {
_super(key, value);
instance.That=function () {
alert('That');
};
});
}
示例代码:
var x=new Xyz('x', '123');
alert([x.Key, x.Value].join(': ')+'; isAbc: '+(x instanceof Abc));
var y=new Xyz('y', '456');
alert([y.Key, y.Value].join(': ')+'; isAbc: '+(y instanceof Abc));
var it=new Abc('it', '789');
alert([it.Key, it.Value].join(': ')+'; isAbc: '+(it instanceof Abc));
alert([it.Key, it.Value].join(': ')+'; isXyz: '+(it instanceof Xyz));
x.What();
y.That();
it.What();
it.That(); // will throw; it is not Xyz and does not have That method
答案 0 :(得分:22)
没有。不,不,这不行。你在JavaScript中做继承都是错的。你的代码给了我偏头痛。
如果你想要类似于JavaScript中的类,那么有很多库可以提供给你。例如,使用augment,您可以按如下方式重新构建代码:
var augment = require("augment");
var ABC = augment(Object, function () {
this.constructor = function (key, value) {
this.key = key;
this.value = value;
};
this.what = function () {
alert("what");
};
});
var XYZ = augment(ABC, function (base) {
this.constructor = function (key, value) {
base.constructor.call(this, key, value);
};
this.that = function () {
alert("that");
};
});
我不了解你,但对我而言,这看起来很像C ++或Java中的经典继承。如果这解决了你的问题,太好了!如果不是,那么继续阅读。
在很多方面,原型与类相似。事实上,原型和类是如此相似,我们可以使用原型来建模类。首先让我们来看看how prototypal inheritance really works:
以上图片来自following answer。我建议你仔细阅读。该图显示了我们:
prototype
的属性,它指向构造函数的原型对象。constructor
的属性,它指向原型对象的构造函数。prototype
,而不是构造函数。这是非常有用的信息。传统上我们总是先创建一个构造函数,然后我们设置它的prototype
属性。但是,这些信息告诉我们,我们可以先创建一个原型对象,然后在其上定义constructor
属性。
例如,传统上我们可以写:
function ABC(key, value) {
this.key = key;
this.value = value;
}
ABC.prototype.what = function() {
alert("what");
};
然而,使用我们新发现的知识,我们可能会写同样的东西:
var ABC = CLASS({
constructor: function (key, value) {
this.key = key;
this.value = value;
},
what: function () {
alert("what");
}
});
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
正如您所看到的,在JavaScript中很容易实现封装。你需要做的就是侧身思考。然而,继承是一个不同的问题。你需要做更多的工作来实现继承。
了解augment
achieves inheritance:
function augment(body) {
var base = typeof this === "function" ? this.prototype : this;
var prototype = Object.create(base);
body.apply(prototype, arrayFrom(arguments, 1).concat(base));
if (!ownPropertyOf(prototype, "constructor")) return prototype;
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
请注意,最后三行与上一节中CLASS
的行相同:
function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}
这告诉我们,一旦我们有了一个原型对象,我们需要做的就是获取它的构造函数属性并返回它。
增强的前三行用于:
Object.create
创建派生类原型。这就是JavaScript中继承的全部内容。如果你想创建自己的经典继承模式,那么你应该按照相同的思路思考。
每个值得他们学习的JavaScript程序员都会告诉你prototypal inheritance is better than classical inheritance。然而,来自具有经典继承的语言的新手总是试图在原型继承之上实现经典继承,并且它们通常会失败。
它们失败的原因不是因为它不可能在原型继承之上实现经典继承,而是因为要在原型继承之上实现经典继承,首先需要了解true prototypal inheritance works。
然而,一旦你理解了真正的原型继承,你就永远不想回到古典继承。作为一个新手,我在原型继承之上的tried到implement经典继承。既然我理解了真正的原型继承是如何工作的,那么我编写这样的代码:
function extend(self, body) {
var base = typeof self === "function" ? self.prototype : self;
var prototype = Object.create(base, {new: {value: create}});
return body.call(prototype, base), prototype;
function create() {
var self = Object.create(prototype);
return prototype.hasOwnProperty("constructor") &&
prototype.constructor.apply(self, arguments), self;
}
}
上述extend
功能与augment
非常相似。但是,它不返回构造函数,而是返回原型对象。这实际上是一个非常巧妙的技巧,它允许继承静态属性。您可以使用extend
创建一个类,如下所示:
var Abc = extend(Object, function () {
this.constructor = function (key, value) {
this.value = 333 + Number(value);
this.key = key;
};
this.what = function () {
alert("what");
};
});
继承就是这么简单:
var Xyz = extend(Abc, function (base) {
this.constructor = function (key, value) {
base.constructor.call(this, key, value);
};
this.that = function () {
alert("that");
};
});
但请记住,extend
不会返回构造函数。它返回原型对象。这意味着您无法使用new
关键字来创建类的实例。相反,您需要使用new
作为方法,如下所示:
var x = Xyz.new("x", "123");
var y = Xyz.new("y", "456");
var it = Abc.new("it", "789");
这实际上是一件好事。 new
关键字为considered harmful,我强烈建议您stop using it。例如,它是not possible to use apply
with the new
keyword。但是,可以将apply
与new
方法一起使用,如下所示:
var it = Abc.new.apply(null, ["it", "789"]);
由于Abc
和Xyz
不是构造函数,我们无法使用instanceof
来测试对象是Abc
还是{{1}的实例}。然而,这不是问题,因为JavaScript有一个名为isPrototypeOf
的方法,它测试一个对象是否是另一个对象的原型:
Xyz
实际上alert(x.key + ": " + x.value + "; isAbc: " + Abc.isPrototypeOf(x));
alert(y.key + ": " + y.value + "; isAbc: " + Abc.isPrototypeOf(y));
alert(it.key + ": " + it.value + "; isAbc: " + Abc.isPrototypeOf(it));
alert(it.key + ": " + it.value + "; isXyz: " + Xyz.isPrototypeOf(it));
比isPrototypeOf
更强大,因为它允许我们测试一个类是否扩展了另一个类:
instanceof
除了这个微小的改变之外,其他一切都像以前一样有效:
alert(Abc.isPrototypeOf(Xyz)); // true
自己查看演示:http://jsfiddle.net/Jee96/
真正的原型继承还能提供什么?真正的原型继承的最大优点之一是,正常属性和静态属性之间没有区别,允许您编写如下代码:
x.what();
y.that();
it.what();
it.that(); // will throw; it is not Xyz and does not have that method
请注意,我们可以通过调用var Xyz = extend(Abc, function (base) {
this.empty = this.new();
this.constructor = function (key, value) {
base.constructor.call(this, key, value);
};
this.that = function () {
alert("that");
};
});
从类本身创建类的实例。如果尚未定义this.new
,则返回新的未初始化实例。否则它返回一个新的初始化实例。
此外,因为this.constructor
是原型对象,我们可以直接访问Xyz
(即Xyz.empty
是empty
的静态属性)。这也意味着静态属性会自动继承,并且与普通属性没有区别。
最后,因为可以在类定义中访问类Xyz
,所以可以使用this
创建嵌套类,这些类通过使用extend
从嵌套到的类继承,如下所示:
var ClassA = extend(Object, function () {
var ClassB = extend(this, function () {
// class definition
});
// rest of the class definition
alert(this.isPrototypeOf(ClassB)); // true
});
自己查看演示:http://jsfiddle.net/Jee96/1/
答案 1 :(得分:3)
答案 2 :(得分:2)
我知道这不能回答你的问题,因为据我所知,没有好办法把所有东西放在函数构造函数中并让它使用原型。
正如我评论的那样;如果您在使用JavaScript语法时遇到问题,那么typescript可能是一个不错的选择。
这是一个帮助函数,我用它来继承和覆盖(调用super)使用JavaScript(没有Object.create)
var goog={};//inherits from closure library base
//http://docs.closure-library.googlecode.com/git/closure_goog_base.js.source.html#line1466
// with modifications for _super
goog.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
// modified _super
childCtor.prototype._super = parentCtor.prototype;
};
// Parent class dev
var Parent = function(){};
Parent.prototype.sayHi=function(){
console.log("hi from Parent");
}
// end class
// Child class dev
var Child = function(){}
goog.inherits(Child,Parent);
Child.prototype.sayHi=function(){
//_super only works on parent.prototype
//this is where functions are usually defined
//have to add this. to call _super as well
this._super.sayHi();
console.log("hi from Child");
}
// end Child
//code to test
var c = new Child();
c.sayHi();//hi from Parent and hi from Child
即使您找到了编写辅助函数的方法并使JS构造函数看起来像Java类,您也必须understand prototype。
答案 3 :(得分:-2)
你总是可以试试jOOP,虽然它确实需要jQuery。
https://github.com/KodingSykosis/jOOP
var myClass = $.cls({
main: function() {
$('body').append('My App is loaded <br/>');
}
});
var mySecondClass = $.cls({
main: function() {
this._super();
$('body').append('My Second App is loaded <br/>');
}
}, myClass);
var app = new mySecondClass();
答案 4 :(得分:-2)
我相信你正在寻找比这更多的功能,但是如果你想从另一个类继承一堆方法你可以做到这一点
var Parent = function Parent () {
this.fname = 'Bob';
this.lname = 'Jones';
};
Parent.prototype.getFname = function getFname () {
return this.fname;
};
Parent.prototype.getLname = function getLname () {
return this.lname;
};
var Child = function Child () {
this.fname = 'Jim';
};
Child.prototype = Parent.prototype;
var child = new Child();
document.write(child.getFname()); //=> Jim