// An highlighted block
<script>
function createPerson(name,age,job){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.job = job;
obj.sleep = function(){
return this.name+"规律";
};
return obj;
}
var person1 = createPerson('zhangsan',20,'wu');
</script>
注释:解决创建多个对象的问题,没办法区分对象的类型
// An highlighted block
<script>
function Person() {
this.name = arguments[0];
this.sex = arguments[1];
this.age = arguments[2];
this.eat = function () {
return this.name + "会吃饭!";
}
}
var son = new Person("小黑", "男", 18);
var son1 = new Person("小花", "女", 18);
console.log(son, son1);
</script>
注释:可以区分类型,但每个方法在每个实例上面都需要重新定义一遍
// An highlighted block
<script>
function Person(){
}
Person.prototype.name = 'panrui';
Person.prototype.age = 23;
Person.prototype.job = '前端工程师';
Person.prototype.speak = function(){
console.log(this.name)
}
var person3 = new Person()
</script>
注释:纯原型构造不能传递参数,但可以实现原型属性的共享
// An highlighted block
<script>
function animal() {
this.name = arguments[0];
this.sex = arguments[1];
this.type = arguments[2]
}
animal.prototype = {
constructor: animal,
eat: function () {
return this.name + "吃饭";
},
sleep: function () {
return this.name + "睡觉";
},
info: function () {
return this.name + "属于:" + this.type + ",性别:" + this.sex;
}
}
//原型模式 会导致所有的原型属性以及方法全部共享
var cat = new animal("喵喵", "母", "猫科");
var mouse = new animal("米奇", "公", "鼠科");
</script>
注释:可以使用原型+构造写法,两个模式相互互补
// An highlighted block
<script>
function Animal(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.speak = "我在讲话";
if (typeof this.speak != "function") {
Animal.prototype.sleep = function () {
console.log(this.name + "在睡觉");
};
}
}
var snack = new Animal("小蛇", 2, '爬');
console.log(snack);
</script>
注释:可以通过相关属性动态添加原型 (检测原型是否存在)
// An highlighted block
<script>
function Instance(name, sex, age) {
var instance = null;
function Animal() {
this.name = arguments[0];
this.sex = arguments[1];
this.age = arguments[2];
}
if (instance == null) {
instance = new Animal(name, sex, age);
}
return instance;
}
var cat = Instance("咪咪", "母", 2);
console.log(cat);
</script>
注释:返回一个对象
// An highlighted block
<script>
var model = (function () {
var instance = null;
var person = null;
function Animal() {
this.name = arguments[0];
this.sex = arguments[1];
this.age = arguments[2];
}
function Person() {
this.name = arguments[0];
this.sex = arguments[1];
this.age = arguments[2];
}
if (person == null) {
person = new Person("maodou", "男", 18);
}
if (instance == null) {
instance = new Animal("cat", "母", 2);
}
return {
instance: instance,
person: person
}
})()
console.log(model);
</script>
注释:相当于代码块的封装