JavaScript Tips: 原型链 prototype

Posted Jane&Coding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=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;

 

原理:补充。

 

以上是关于JavaScript Tips: 原型链 prototype的主要内容,如果未能解决你的问题,请参考以下文章

#yyds干货盘点#JavaScript之彻底理解原型与原型链

深入理解JS原型与原型链

关于JS原型以及原型链instanceof的一些理解

JS函数高级

JavaScript中原型与原型链

JavaScript扩展原型链浅析