这里介绍一种基于组合的对象定义
为了解决原型所带来的问题,需要通过组合构造函数和原型来实现对象的创建:将属性在构造函数中定义,将方法在原型中定义。这样有效结合了基于原型链和构造函数来定义对象的有点,是目前最为常用的一种方式。
代码演示如下:
<!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>
运行结果:
![这里写图片描述](https://img-blog.csdn.net/20161010201943731)
此时的内存模块图如下所示:
![这里写图片描述](https://img-blog.csdn.net/20161010204815300)
这里介绍另外一种基于动态原型的对象定义(选学)
代码演示如下:
<!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>
运行结果:
![这里写图片描述](https://img-blog.csdn.net/20161010202727663)