封装--javascript的原型(prototype)
2016-10-10 20:27
459 查看
这里介绍一种基于组合的对象定义
为了解决原型所带来的问题,需要通过组合构造函数和原型来实现对象的创建:将属性在构造函数中定义,将方法在原型中定义。这样有效结合了基于原型链和构造函数来定义对象的有点,是目前最为常用的一种方式。代码演示如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> //属性在构造方法中定义 function Person(name,age,friends){ this.name=name; this.age=age; this.friends=friends; } //将方法定义在原型中 Person.prototype={ constructor:Person, say:function(){ console.log("my name is :"+this.name+",age is :"+this.age); } }; var p1=new Person("liyanan",13,["lh","jc"]); p1.friends.push("ld"); console.log(p1.friends); p1.say(); var p2=new Person("lyn",13,["lys","lc"]); console.log(p2.friends); p2.say(); </script> </head> <body> </body> </html>
运行结果:
此时的内存模块图如下所示:
这里介绍另外一种基于动态原型的对象定义(选学)
代码演示如下:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> //属性在构造方法定义 function Person(name,age,friends){ this.name=name; this.age=age; this.friends=friends; //判断不存在的时候写,如果存在就不写,内存减少消耗 if(!Person.prototype.say){ Person.prototype.say=function(){ console.log("my name is :"+this.name+",age is :"+this.age); } } } var p1=new Person("liyanan",13,["lh","jc"]); p1.friends.push("ld"); console.log(p1.friends); p1.say(); var p2=new Person("lyn",13,["lys","lc"]); console.log(p2.friends); p2.say(); </script> </head> <body> </body> </html>
运行结果:
相关文章推荐
- 【JavaScript 封装库】Prototype 原型版发布!
- 封装——JavaScript的原型(prototype)
- JavaScript 利用prototype原型实现封装继承多态
- JavaScript使用prototype原型实现的封装继承多态示例
- 【JavaScript 封装库】Prototype 原型版发布!
- JavaScript prototype原型和原型链详解
- javascript之prototype原型属性案例
- javascript原型继承分析(prototype)
- Javascript玩转Prototype(一)——先谈C#原型模式
- JavaScript中如何使用原型方法--prototype
- 剖析JavaScript中的原型(Prototype)
- javascript prototype原型修改
- 理解JavaScript原型prototype
- javascript中的原型链,prototype与__proto__的关系
- JavaScript引用类型之原型prototype
- Javascript对象原型prototype和继承
- JavaScript 的 Prototype 原型链详解(转)
- 从0开始学react netive:2.Javascript创建对象的方式_prototype原型的概念_原型继承
- Javascript学习笔记九——prototype封装继承
- JavaScript中的原型prototype属性使用详解