Possible Duplicate:
Calling base method using JavaScript prototype
我想要继承对象,它将覆盖 javascript 中的函数。
从我要调用的方法到基方法。
在这种情况下,我从 Person
继承了对象 reader
,现在我想重写函数 getName
,这意味着在 reader 中我首先要调用该函数在 Person
上,然后做一些改变。
<script>
/* Class Person. */
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
var reader = new Person('John Smith');
reader.getName = function() {
// call to base function of Person, is it possible?
return('Hello reader');
}
alert(reader.getName());
</script>
Vincent 回答了你的直接问题,但如果你想建立一个真正的继承层次结构,你可以在其中进一步扩展 Reader
,那么你应该怎么做。
创建你的 person 类:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(){
alert('Person getName called for ' + this.name);
return this.name;
}
同时创建一个 Reader 类:
function Reader(name) {
// Calls the person constructor with `this` as its context
Person.call(this, name);
}
// Make our prototype from Person.prototype so we inherit Person's methods
Reader.prototype = Object.create(Person.prototype);
// Override Persons's getName
Reader.prototype.getName = function() {
alert('READER getName called for ' + this.name);
// Call the original version of getName that we overrode.
Person.prototype.getName.call(this);
return 'Something';
}
Reader.prototype.constructor = Reader;
现在我们可以重复类似的过程来扩展 Reader,例如使用 VoraciousReader:
function VoraciousReader(name) {
// Call the Reader constructor which will then call the Person constructor
Reader.call(this, name);
}
// Inherit Reader's methods (which will also inherit Person's methods)
VoraciousReader.prototype = Object.create(Reader.prototype);
VoraciousReader.prototype.constructor = VoraciousReader;
// define our own methods for VoraciousReader
//VoraciousReader.prototype.someMethod = ... etc.
fiddle :
http://jsfiddle.net/7BJNA/1/
对象创建:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
Object.create(arg)
正在创建一个新对象,其原型(prototype)是作为参数传入的对象。
编辑
距离这个最初的答案已经有好几年了,现在 Javascript 支持 class
关键字,如果您来自 Java 或 C++ 等语言,它可以像您期望的那样工作。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes