利用原型来共享数据
- 不需要共享的数据写在构造函数中,需要共享的数据写在原型中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function Person(name,age) {
this.name=name;
this.age=age;
}
Person.prototype.height="180";
Person.prototype.play=function () {
console.log("我们都喜欢玩耍");
};
Person.prototype.eat=function () {
console.log("但是我们跟喜欢吃好吃的");
};
var person=new Person("张雨生",18);
console.dir(Person);
console.dir(person);
</script>
</body>
</html>
原型简单语法的书写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function Person(name,age) {
this.name=name;
this.age=age;
}
Person.prototype={
constructor:Person,
height:"180",
weight:"50kg",
play:function () {
console.log("我们都喜欢玩耍");
},
eat:function () {
console.log("但是我们跟喜欢吃好吃的");
}
};
var person=new Person("张雨生",18);
console.dir(Person);
console.dir(person);
</script>
</script>
</body>
</html>
实例对象的方法是可以相互调用的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function Person(name,age) {
this.name=name;
this.age=age;
this.play=function () {
console.log("我们都喜欢玩耍");
this.eat();
};
this.eat=function () {
console.log("但是我们跟喜欢吃好吃的");
};
}
Person.prototype={
constructor:Person,
height:"180",
weight:"50kg"
};
var person=new Person("张雨生",18);
person.play();
</script>
</body>
</html>
原型中的方法也是可以相互调用的
不能互调,不然会进入死循环
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function Animal(name,age) {
this.name=name;
this.age=age;
}
Animal.prototype.eat=function () {
console.log("动物吃东西");
this.play();
};
Animal.prototype.play=function () {
console.log("玩球");
this.sleep();
};
Animal.prototype.sleep=function () {
console.log("睡觉了");
};
var dog=new Animal("小王",20);
dog.eat();
</script>
</body>
</html>