我已经更改了现在的操作方式,我尝试避免使用构造函数和它们的
prototype属性,但是我从2010年起的旧答案仍然是最底层的。我现在更喜欢
Object.create()。
Object.create适用于所有现代浏览器。
我应该注意,这
Object.create通常比使用函数构造函数慢得多
new。
//The prototype is just an object when you use `Object.create()`var base = {};//This is how you create an instance:var baseInstance = Object.create(base);//If you want to inherit from "base":var subInstance = Object.create(Object.create(base));//Detect if subInstance is an instance of base:console.log(base.isPrototypeOf(subInstance)); //True使用Object.create的最大好处之一就是能够传递defineProperties参数,该参数使您可以有效控制如何访问和枚举类的属性,并且我还使用函数来创建实例,这些函数可以用作构造函数,因为您可以在最后进行初始化,而不仅仅是返回实例。
var base = {};function createbase() { return Object.create(base, { doSomething: { value: function () { console.log("Doing something"); }, }, });}var Sub = createbase();function createSub() { return Object.create(Sub, { doSomethingElse: { value: function () { console.log("Doing something else"); }, }, }); }var subInstance = createSub();subInstance.doSomething(); //Logs "Doing something"subInstance.doSomethingElse(); //Logs "Doing something else"console.log(base.isPrototypeOf(subInstance)); //Logs "true"console.log(Sub.isPrototypeOf(subInstance)); //Logs "true这是我2010年的原始答案:
function base ( ) { this.color = "blue";}function Sub ( ) {}Sub.prototype = new base( );Sub.prototype.showColor = function ( ) { console.log( this.color );}var instance = new Sub ( );instance.showColor( ); //"blue"


