这是一种使用原型继承的方法,. 要查看控制台输出,请在 Chrome 中按 F12 或在 FireFox 中打开 FireBug。Chrome 会给你一个交互式对象来深入研究。
function monsterMaker() {
this.type = "monster";
this.health = 10;
}
function squeek() {
this.name = "squeek";
//monsterMaker.call(this); // sets properties on this
}
squeek.prototype = new monsterMaker();
squeek.prototype.constructor = monsterMaker;
var squeaker = new squeek();
console.log(squeaker);
console.log(squeaker.name);
console.log(squeaker.type);
console.log(squeaker.health);
在这里看到它的工作:
http://www.quirkscode.com/flat/forumPosts/extendThis/extendThis.html
以下是一些链接:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_Revisited
从上面的第二个 MDN 链接中提取,您可以使用“新 JavaScript 方式”(ECMAScript 5)因此(包括用于扩展和示例代码的库 - 使用控制台查看示例输出:
// Original Author: FireFly - Jonas Höglund - ##javascript channel
// on irc.freenode.net - see THANKS File
///////////////
// Library code
///////////////
var ExtendBase = {};
Object.defineProperty(ExtendBase, 'extend', {
enumerable: false
, value: function(obj) {
'use strict';
var descs = {}
, objectInheritCounter = 0;
objectInheritCounter += 1;
Object.getOwnPropertyNames(obj).forEach(function(key) {
descs[key] = Object.getOwnPropertyDescriptor(obj, key)
});
return Object.create(this, descs);
}
});
///////////////
// Sample Usage
///////////////
var Person = ExtendBase.extend({
// missing: name
// A person can tell you its name.
talk: function() {
return "Hello, I'm " + this.name
}
})
var WorkingPerson = Person.extend({
// missing: name, occupation
// A working person also tells you their occupation when they talk.
talk: function() {
return Person.talk.call(this) + " and I am a " + this.occupation
}
})
var p1 = WorkingPerson.extend({ name:"Harry", occupation:"wizard" })
console.log(p1.talk()); // "Hello, I'm Harry and I am a wizard"
在这里看到它的工作:
http://www.quirkscode.com/flat/JSLearning/src/extend/extend.html