创建对象的方式大致有以下三种,根据使用的目的不同可以选择适合的方法
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>创建对象</title>
<script type="text/javascript">
function foo() {} //打酱油的外部方法
/*创建对象的第一种方式: JSON*/
var stu = { name: 'Abe', age: 30, friendNames: ['Zoo', 'Natu'],
play: function() {}, eat: foo };
//只针对自己调用时,直接给出属性和方法 (新建的对象的类型为Object)
/*创建对象的第二种方式: 构造器函数(混合模式)*/
//构造器函数和原型模式的混合模式,上半部分为构造器函数模式 (新建对象的类型为指定类型)
function Person(name, age) {
this.name = name;
this.age = age;
}
//原型模式:原型包含所有的共享的属性和方法 用prototype赋值给原型
Person.prototype.play = function(game) {
window.alert(this.name + "正在玩" +game);
};
Person.prototype.eat = function() {
window.alert(this.name + "正在吃饭");
};
//实验
var p1 = new Person("Abe", 30);
p1.play("三国杀");
p1.eat();
window.alert(p1 instanceof Person);
/*创建对象的第三种方式: 工厂模式*/
//工厂模式,创建多个相似对象时使用 (新建对象类型为Object)
function createPerson(name, age) {
var obj = new Object();
obj.name = name;
obj.age = age;
obj.play = function(game) {
window.alert(this.name + "正在玩" +game);
};
obj.eat = function() {
window.alert(this.name + "正在吃饭");
};
return obj;
}
var p2 = createPerson("Zoo", 20);
window.alert(p2["name"]);
p2.play("大富翁");
p2.eat();
window.alert("name" in p2 && "eat" in p2 && "play" in p2);
// 对于1和3种方法,无法直接用类型来判断其类型 所以只能用 鸭子判定法
// 鸭子判定法:拥有指定的属性和方法,就视为一个类型
</script>
</head>
<body>
</body>
</html>