JavaScript的中对象创建和继承原理
2013-02-28 10:11
323 查看
[b]对象创建:[/b]
当一个函数对象被创建时候,Function构造器产生的函数对象会运行类似这样的代码:
this.prototype={constructor:this};
假设函数F
F用new方式构造对象时,对象的constructor被设置成这个F.prototype.constructor
如果函数在创建对象前修改了函数的prototype,会影响创建出来对象的construtor属性
如:
[b]继承原理:[/b]
JavaScript中的继承是使用原型链的机制,每个函数的实例都共享构造函数prototype属性中定义的数据,要使一个类继承另一个,需要把父函数实例赋值到子函数的prototype属性。并且在每次new实例对象时,对象的私有属性__proto__会被自动连接到构造函数的prototype。
instanceof就是查找实例对象的私有prototype属性链来确定是否是指定对象的实例
具体实例:
上面自定义的Myinstanceof就是自己实现的一个instanceof功能的函数,由于IE内核实例存储prototype不是__proto__,所以Myinstanceof会无法通过,其他浏览器上应该都没有问题
当一个函数对象被创建时候,Function构造器产生的函数对象会运行类似这样的代码:
this.prototype={constructor:this};
假设函数F
F用new方式构造对象时,对象的constructor被设置成这个F.prototype.constructor
如果函数在创建对象前修改了函数的prototype,会影响创建出来对象的construtor属性
如:
function F(){}; F.prototype={constructor:'1111'}; var o=new F();//o.constructor===‘1111’ true
[b]继承原理:[/b]
JavaScript中的继承是使用原型链的机制,每个函数的实例都共享构造函数prototype属性中定义的数据,要使一个类继承另一个,需要把父函数实例赋值到子函数的prototype属性。并且在每次new实例对象时,对象的私有属性__proto__会被自动连接到构造函数的prototype。
instanceof就是查找实例对象的私有prototype属性链来确定是否是指定对象的实例
具体实例:
//instanceof实现 function Myinstanceof(obj,type) { var proto=obj.__proto__; while(proto) { if(proto ===type.prototype)break; proto=proto.__proto__; } return proto!=null; } function View(){} function TreeView(){} TreeView.prototype=new View();//TreeView.prototype.__proto__=TreeView.prototype 自动完成 TreeView.prototype.constructor=TreeView;//修正constructor var view=new TreeView();//view.__proto__=TreeView.prototype 自动完成 alert(view instanceof View); //true 查找到view.__proto__.__proto__时找到 alert(view instanceof TreeView); //true 查找到view.__proto__时找到 alert(Myinstanceof(view,View)); //true alert(Myinstanceof(view,TreeView)); //true
上面自定义的Myinstanceof就是自己实现的一个instanceof功能的函数,由于IE内核实例存储prototype不是__proto__,所以Myinstanceof会无法通过,其他浏览器上应该都没有问题
相关文章推荐
- JavaScript对象创建及继承原理实例解剖
- JavaScript的中对象创建和继承原理
- JavaScript的中对象创建和继承原理
- JavaScript对象创建及继承原理实例解剖
- javascript高级程序设计一书----关于创建和对象继承的总结
- Javascript笔记:jQuery源码分析以及从jQuery对象创建的角度理解extend方法的原理
- JavaScript创建对象与继承
- Java程序员从笨鸟到菜鸟之(二十九)javascript对象的创建和继承实现
- javascript 创建对象与继承总结和回顾
- Java程序员从笨鸟到菜鸟之(二十九)javascript对象的创建和继承实现
- 在没有类的情况下,JavaScript如何创建对象、实现继承?
- javascript的函数、创建对象、封装、属性和方法、继承
- javascript 创建对象——类,继承
- JavaScript中创建对象和继承示例解读
- JavaScript面向对象中的属性,对象创建,继承
- JavaScript2种构造函数创建对象的模式以及继承的实现
- JAVASCRIPT 对象的创建和对6种继承模式的理解和遐想
- Java程序员从笨鸟到菜鸟之(二十九)javascript对象的创建和继承实现
- Java程序员从笨鸟到菜鸟之(二十九)javascript对象的创建和继承实现
- javascript的函数、创建对象、封装、属性和方法、继承