首页 > 代码库 > JavaScript Tips: 原型链 prototype

JavaScript Tips: 原型链 prototype

 

当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=http://www.mamicode.com/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=http://www.mamicode.com/42;
    }
    Foo.prototype = {
    method:function(){console.log(‘method log‘)}
};
function Bar(){}
Bar.prototype = Foo.prototype;
Bar.prototype.foo = ‘Hello world‘;
Bar.prototype.constructor=Bar;

 

原理:补充。

 

JavaScript Tips: 原型链 prototype