javascript prototype继承对象的属性和方法

来源:互联网 发布:网盘搜索 知乎 编辑:程序博客网 时间:2024/05/02 04:15

运行环境chrom console

一、prototype

>function a(){this.a1='123';this.a2="456";}

undefined


>function b(){this.b1='b123';this.b2="b456";}

undefined


>var bb = new b();

undefined


>bb.b1

"b123"


>b.prototype = new a();

a {a1: "123", a2: "456"}


>var bb = new b();

undefined


>bb.b1;

"b123"


>bb.a1

"123"


二、__proto__

>function a(){this.a1="a123";this.a2="a456";}
undefined


>function b(){this.b1="b123";this.b2="b456";}

undefined

>b.prototype = new a();
a {a1: "a123", a2: "a456"}


>var bbb = new b();
undefined


>bbb.b1
"b123"


>bbb.__proto__
a {a1: "a123", a2: "a456"}

可见对象的__proto__属性指向类的prototype属性。如实例:bbb.__proto__ -> b.prototype


>bbb.__proto__

a {a1: "a123", a2: "a456"} 

返回a类型的对象


>bbb.__proto__.__proto__

a{}

因为bbb.__proto__返回的是a类型的对象,而且a.prototype指向a{},所以bbb.__proto__.__proto__指向a{}


三、constructor (创建对象)

>function test(){}


>test.constructor

function Function() { [native code] }  //test函数的constructor指向function对象的构造函数,所以new test()会创建一个函数对象。


>var t = new test();


>t.constructor === t.__proto__.constructor

true  //test类的对象constructor,t.constructor 指向 t.__proto__.constructor


总结:对象通过__proto__向上寻找原型对象。这样可以达到链式继承目的


1 0