交互式爱情
我现在已经改变了我的方法,我尽量避免使用构造函数及其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的jsfiddle使用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的jsfiddle这是我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"