码迷,mamicode.com
首页 > Web开发 > 详细

JS继承之prototype

时间:2017-03-16 18:42:43      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:upper   this   efi   function   instance   undefined   ons   get   静态属性   

function SuperFun(){
  this.proper = ‘1‘;
}
SuperFun.localProper = ‘a‘;
SuperFun.prototype.name = ‘supperName‘;
SuperFun.prototype.getName = function(){console.info(this.name);};
var superInstance = new SuperFun();
function SubFun(){
  this.subProper = ‘2‘;
}
SubFun.prototype.subName = ‘subName‘;
SubFun.prototype = new SuperFun();
var subInstance = new SubFun();

console.info(superInstance.localProper); //undefined,这是来捣乱的,localProper是S构造函数的静态属性,实例是访问不了的
console.info(subInstance.subName);       //undefined,因为在SubFun继承SuperFun的时候,SubFun.prototype先被赋值为{},之前原型的属性都没了
console.info(subInstance.subProper);     //可以被访问的到
console.info(subInstance.name);          //可以被访问的到
console.info(subInstance.proper);        //可以被访问的到
console.info(subInstance.__proto__); 
console.info(subInstance.__proto__.__proto__); 
console.info(subInstance.__proto__.__proto__.__proto__);   //找到了Object的prototype,到最顶层了
console.info(subInstance.constructor); 

 输出结果如下:

技术分享

console.info(subInstance.__proto__); 输出为:
技术分享
在SubFun没有继承之前,SubFun的原型是SubFun.prototype,继承时,进行如下三步操作:
SubFun.prototype = {}
SubFun.Prototy.__proto__ = SuperFun.prototype
SuperFun.call(SubFun.prototype),这步执行后,将SuperFun构造函数的super属性添加到了SubFun.prototype中去。

 

JS继承之prototype

标签:upper   this   efi   function   instance   undefined   ons   get   静态属性   

原文地址:http://www.cnblogs.com/wangxuehao/p/6560757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!