您的位置:首页 > Web前端 > JavaScript

封装--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>


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息