// Object构造函数
var bird = new Object();
bird.name = 'jack';
bird.age = 1;
bird.color = 'black';
bird.sayHi = function () {
console.log('Hi~,i\'m' + bird.name + '|' + bird.age + '|' + bird.color + '。');
}
bird.sayHi();
// 字面量创建
var fish = {
name: 'lili',
age: 2,
color: 'red',
sayHi: function () {
console.log('Hi~,i\'m' + this.name + '|' + this.age + '|' + this.color + '。');
}
}
fish.sayHi();
// 工厂模式创建对象
// 解决了代码重复但是没有解决对象识别问题
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayHi = function () {
console.log('Hi~,i\'m' + o.name + '|' + o.age + '|' + o.job + '。');
}
return o;
}
var p1 = createPerson('LiHua', 22, 'chef');
var p2 = createPerson('ZhangSan', 23, 'programmer');
p1.sayHi();
p2.sayHi();
console.log(typeof p1);
console.log(p1 instanceof createPerson)
// 构造函数模式
// 每个方法都会在实例上重新创建一遍
function Dog(name, age, color) {
this.name = name;
this.age = age;
this.color = color;
this.sayHi = function () {
console.log('Hi~,i\'m' + this.name + '|' + this.age + '|' + this.color + '。');
}
}
var d1 = new Dog('LiHua', 22, 'white');
var d2 = new Dog('ZhangSan', 23, 'grey');
d1.sayHi();
d2.sayHi();
console.log(typeof d1);
console.log(d1 instanceof Dog)
// 原型模式
function Cat() {
}
Cat.prototype.name = 'mimi';
Cat.prototype.age = 3;
Cat.prototype.color = 'orange';
Cat.prototype.sayHi = function () {
console.log('Hi~,i\'m' + this.name + '|' + this.age + '|' + this.color + '。');
}
var cat1 = new Cat();
cat1.sayHi();
console.log(Object.getPrototypeOf(cat1).age);
console.log(Object instanceof Dog);
// 组合模式
function Tiger(name, age, color) {
this.name = name;
this.age = age;
this.color = color;
this.food = ['fish', 'dog', 'chicken'];
}
Tiger.prototype = {
constructor: Tiger, // 字面量赋值会使constructor指向Object
sayHi: function () {
console.log(`我是老虎,我叫${this.name};${this.age}岁;有一身${this.color}的毛;喜欢吃${this.food.toString()}`);
}
}
var tiger1 = new Tiger('欢欢', 3, '黄色');
tiger1.food.push('斑马');
tiger1.sayHi();
var tiger2 = new Tiger('团团', 2, '白色');
tiger2.sayHi();
// 动态原型模式
function Lion(name, age, color) {
this.name = name;
this.age = age;
this.color = color;
if (typeof Lion.prototype.sayHi !== 'function') {
Lion.prototype = {
sayHi: function () {
console.log(`我是狮子,我叫${this.name};${this.age}岁;有一身${this.color}的毛`);
}
}
}
}
var lion1 = new Lion('奥利奥',4,'金色');
// lion1.sayHi();
var lion2 = new Lion('奥利佛',5,'棕色');
lion2.sayHi();
console.log(lion2.sayHi === lion1.sayHi);
function Person(name, age, job) {
// 创建要返回的对象
var o = new Object();
o.name = name;
// 定义私有变量和函数
// 添加方法
o.sayName = function() {
console.log(name);
}
// 返回对象
return o;
}
var friend = new Person('LiHua', 22, 'Software Engineer');
friend.sayName();
console.log(friend instanceof Person);
var friend2 = new Person('LiHua2', 22, 'Software Engineer');
friend2.sayName();
console