说我在JS中有原型函数的classe ...
function Foo() {
this.stuff = 7;
this.otherStuff = 5;
}
Foo.prototype.doSomething = function() { };
Foo.prototype.doSomethingElse = function() { };
Run Code Online (Sandbox Code Playgroud)
现在说我想通过继承它来"扩展"这个类.在Java中,这看起来像......
public class Bar extends Foo {}
Run Code Online (Sandbox Code Playgroud)
现在我知道在JS中确实没有类的概念,一切都可以改变,而且这一切真的只是归结为一大堆字典但是,尽管如此,我应该能够复制一个类的原型并附加它对另一个原型,对吧?
在香草JS中,这样的代码会是什么样子?
其中一种方式如下所示,
function Foo() {
this.stuff = 7;
this.otherStuff = 5;
}
Foo.prototype.doSomething = function() { alert("some"); };
Foo.prototype.doSomethingElse = function() { };
function Bar() {
Foo.call(this); // this line
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar();
b.doSomething();
Run Code Online (Sandbox Code Playgroud)
像这样的东西...
function Bar(){
// your code
}
Bar.prototype = new Foo(); // Bar extends Foo
Run Code Online (Sandbox Code Playgroud)