对于父/子类,我会做这样的事情
// your parent class
var Parent = function() {
// parent constructor
console.log("parent constructor!");
// some public properties
this.foo = "foo";
this.bar = "bar";
// a private data member
var secret = "123456";
};
// a parent function
Parent.prototype.something = function() {
console.log("something!");
}
// your child class
var Child = function() {
// call parent constructor
Parent.call(this);
// child constructor
console.log("child constructor!");
// override bar
this.bar = "override!";
};
// the magic!
// child prototype build from parent prototype
Child.prototype = Object.create(Parent.prototype, {constructor: {value: Child}});
示例用法
var c = new Child();
c.something();
// => parent constructor!
// => child constructor!
// => something!
c.foo //=> "foo"
c.bar //=> "override!"
如果您使用“命名空间”,则概念是相同的。
编辑
根据您的评论,这是并添加了演示
var Foo = function(){};
Foo.prototype.hello = function(){ return "hello!"; };
var foo = new Foo();
// call our hello method
// this calls foo.__proto__.hello
foo.hello(); //=> "hello!"
// override `hello` method for this instance
foo.hello = function(){ return "こんにちは"; };
// call our hello method again
// this calls foo.hello because it is defined directly on our instance
// (it has a higher precedence in the lookup chain)
foo.hello(); //=> "こんにちは"
// remove the override
delete foo.hello;
// call our hello method again
// this goes back to calling foo.__proto__.hello
foo.hello(); //=> "hello!"
// remove the method prototype
delete Foo.prototype.hello
// call our hello method one last time
// spoiler: it's gone!
foo.hello(); //=> TypeError: Object [object Object] has no method 'hello'
如您所见,通过使用this.something = function(){};
. 我个人更喜欢在原型上定义方法,因为它增加了灵活性。这样,原型就真的像蓝图一样工作。你得到所有预定义的行为;您可以根据需要进行修改并随时恢复为原始版本,所有这些都基于每个实例。
还有一件事
在上一个示例中,我们有一个原型方法和一个实例方法覆盖。有没有办法调用原始方法?让我们来看看!
var Foo = function(){};
Foo.prototype.hello = function(){ return "hello!"; };
var foo = new Foo();
foo.hello = function(){ return "こんにちは!"; }
// call override method
foo.hello(); //=> "こんにちは!"
// call original method
Foo.prototype.hello.call(foo); //=> "hello!"
// japanese just one more time...
foo.hello(); //=> "こんにちは!"
这也可以,但我从来没有真正需要。我想这样做的好处是您不需要以这种方式了解原始课程:)
// call original method from the instance
foo.__proto__.hello.call(foo); //=> "hello!"
原型!