当 Bar.prototype = new Foo();
- $(function() {
- var test = new Bar();
- console.log(test); //Bar
- test.method(); //method log
- console.log(test.foo); //Hello World
- console.log(test.value); //42
- var footest = new Foo();
- console.log(footest); //Foo
- console.log(footest.foo); //undefined
- console.log(footest.value); //42
- });
- function Foo() {
- this.value = 42;
- }
- Foo.prototype = {
- method: function() {
- console.log('method log')
- }
- };
- function Bar() {}
- Bar.prototype = new Foo();
- Bar.prototype.foo = 'Hello world';
- Bar.prototype.constructor = Bar;
当 Bar.prototype=Foo.prototype;
- $(function() {
- var test = new Bar();
- console.log(test); //Bar
- test.method(); //method log
- console.log(test.foo); //Hello World
- console.log(test.value); //undefined
- var footest = new Foo();
- console.log(footest); //Foo
- console.log(footest.foo); //Hello World
- console.log(footest.value); //42
- });
- function Foo() {
- this.value = 42;
- }
- Foo.prototype = {
- method: function() {
- console.log('method log')
- }
- };
- function Bar() {}
- Bar.prototype = Foo.prototype;
- Bar.prototype.foo = 'Hello world';
- Bar.prototype.constructor = Bar;
原理:补充。
来源: