When it comes to inheritance, there is only one data type in js: object. Every object has a private property named \ _proto___ which points to its prototype. The top of the prototype is Object . Object.__proto__ === null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 let f = function ( ) { this .a = 1 ; this .b = 2 ; } let o = new f(); f.prototype.b = 3 ; f.prototype.c = 4 ;
1 2 3 4 5 6 function doSomething ( ) {}console .log( doSomething.prototype );var doSomething = function ( ) {};console .log( doSomething.prototype );
1 2 3 4 5 6 7 8 9 10 11 12 { constructor : ƒ doSomething(), __proto__: { constructor : ƒ Object(), hasOwnProperty: ƒ hasOwnProperty(),//return a boolean isPrototypeOf: ƒ isPrototypeOf(),//return a boolean on whether inherit propertyIsEnumerable: ƒ propertyIsEnumerable(),//是否可枚举 toLocaleString: ƒ toLocaleString(),//可输出日期等 toString: ƒ toString(),// valueOf: ƒ valueOf() } }
4 ways to lengthen the prototype link New 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function foo ( ) {}foo.prototype = { foo_prop: "foo val" } var proto = new foo proto.bar_prop = "bar val" function bar ( ) {}bar.prototype = proto var inst = new barconsole .log(inst.__proto__ === bar.prototype)console .log(inst.__proto__ === proto)console .log(bar.prototype === proto)console .log(proto.__proto__ === foo.prototype)console .log(proto.__proto__ === foo.prototype)
Object.create 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 function foo ( ) {}foo.prototype = { foo_prop: "foo val" }; function bar ( ) {}var proto = Object .create( foo.prototype, { bar_prop: { value: "bar val" } } ); bar.prototype = proto; var inst = new bar;console .log(inst.foo_prop);console .log(inst.bar_prop);
IE8 unsupported
Object.setPrototypeOf perform badly
__proto__ need abandoning
prototype
和 Object.getPrototypeOf
1 2 3 var a1 = new A(); var a2 = new A();Object .getPrototypeOf(a1).doSomething == Object .getPrototypeOf(a2).doSomething == A.prototype.doSomething