这是一种与原型继承来做到这一点。要查看控制台输出,请在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
您不能更改此参考。 –