Moo*_*oon 25 javascript inheritance
假设我有以下代码段.
function test(id) { alert(id); }
testChild.prototype = new test();
function testChild(){}
var instance = new testChild('hi');
Run Code Online (Sandbox Code Playgroud)
有可能得到alert('hi')吗?我undefined现在明白了.
roy*_*rie 101
JS OOP ......
// parent class
var Test = function(id) {
console.log(id);
};
// child class
var TestChild = function(id) {
Test.call(this, id); // call parent constructor
};
// extend from parent class prototype
TestChild.prototype = Object.create(Test.prototype); // keeps the proto clean
TestChild.prototype.constructor = TestChild; // repair the inherited constructor
// end-use
var instance = new TestChild('foo');
Run Code Online (Sandbox Code Playgroud)
Sk6*_*606 16
你已经有了很多答案,但我会抛出ES6的方式,恕我直言是这种方式的新标准方式.
class Parent {
constructor() { alert('hi'); }
}
class Child extends Parent {
// Optionally include a constructor definition here. Leaving it
// out means the parent constructor is automatically invoked.
constructor() {
// imagine doing some custom stuff for this derived class
super(); // explicitly call parent constructor.
}
}
// Instantiate one:
var foo = new Child(); // alert: hi
Run Code Online (Sandbox Code Playgroud)
这就是你在CoffeeScript中这样做的方法:
class Test
constructor: (id) -> alert(id)
class TestChild extends Test
instance = new TestChild('hi')
Run Code Online (Sandbox Code Playgroud)
不,我没有开始圣战.相反,我建议看看生成的JavaScript代码,看看如何实现子类化:
// Function that does subclassing
var __extends = function(child, parent) {
for (var key in parent) {
if (Object.prototype.hasOwnProperty.call(parent, key)) {
child[key] = parent[key];
}
}
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
// Our code
var Test, TestChild, instance;
Test = function(id) { alert(id); };
TestChild = function() {
TestChild.__super__.constructor.apply(this, arguments);
}; __extends(TestChild, Test);
instance = new TestChild('hi');
// And we get an alert
Run Code Online (Sandbox Code Playgroud)
在http://jsfiddle.net/NGLMW/3/上查看它的实际操作.
为了保持正确,与CoffeeScript输出相比,代码稍作修改并注释为更具可读性.
| 归档时间: |
|
| 查看次数: |
28355 次 |
| 最近记录: |