demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function myFunction(){
//....
}
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
// this.sayHello = function () {
// console.log("你好我是" + this.name); // 每个对象都使用不同的函数,浪费内存。
// }
// this.sayHello = myFunction; // myFunction是外部定义好的函数(所有对象使用相同的函数),但是造成全局变量污染。因此要使用原型prototype。
}
var p =new Person("张学友",18,"male");
var p1 = new Person("刘德华",19,"male");
Person.prototype.sayHello = function () {
console.log("你好我是" + this.name);
}
Person.prototype["sing"] = function () {
console.log("一千个伤心的理由");
}
p.sayHello();
p1.sayHello();
p.sing();
p1.sing();
//如何使用原型来解决构造函数存在的问题?(全局变量污染的问题 以及 代码结构混乱的问题)
//构造函数的原型对象中的成员,可以被该构造函数创建出来的所有对象访问
//而且,所有的对象共享该对象
//所以,我们可以将构造函数中需要创建的函数,放到原型对象中存储
//这样就解决 全局变量污染的问题 以及 代码结构混乱的问题
</script>
</head>
<body>
</body>
</html>