06JS高级创建对象使用原型共享对象方法

时间:2023-03-09 19:18:13
06JS高级创建对象使用原型共享对象方法
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
function person(age, name) {
this.age = age;
this.name = name;
}
//prototype (相同于某个"类"的共享成员表) 用这样定义的方法,他的对象就会共享该方法
person.prototype.sayHi = function () {
alert("age=" + this.age + ",name=" + this.name);
}
var p1 = new person(12, "刘德华");
p.sayHi(); var p2 = new person(21, "习平");
p2.sayHi(); //通过call方法模拟new关键字创建对象
//var p3 = new Object();
//person.call(p3, 99, "神州");//将对象person方法的this,person 方法为对象添加属性
//p3.sayHi(); </script>
</head>
<body>
</body>
</html>

相关文章