"use strict";
// *****************************************************************
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function(){alert(this.name);};
"use strict";
// *****************************************************************
var person = {
name: "Nicholas",
age: 29,
job: "Software Engineer",
sayName: function(){alert(this.name);}
};
"use strict";
// 工厂模式
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function() {
console.log(this.name);
}
return o;
}
var person1 = createPerson("name1", 1, "hehe");
console.log(person1);
"use strict";
// 构造函数模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function() {
console.log(this.name);
}
}
var person1 = new Person("name2", 2, "hehe");
console.log(person1);
// 检测对象类型
console.log(person1.constructor == Object); // false
console.log(person1.constructor == Person); // true
console.log(person1 instanceof Object); // true
console.log(person1 instanceof Person); // true
// 当作构造函数使用
var person2 = new Person("name3", 3, "hehe");
person2.sayName();
// 作为普通函数调用
// Person("name4", 4, "hehe"); // 添加到window,严格模式下无法访问
// window.sayName(); // name4
// 在另一个对象的作用域中调用
var o = new Object();
Person.call(o, "name5", 5, "111"); // 在对象o中调用
o.sayName(); // o就拥有了所有属性和sayName()方法
// 创建两个完成同样任务的Function实例是没必要的,有this对象在,不需要在执行代码前就把函数绑定到特定对象上面
console.log(person1.sayName == person2.sayName); // false,但方法是相同的
// 通过把函数定义转移到构造函数外来解决
function Person2(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = sayName2;
}
function sayName2() { // 在这种情况下person1和person2共享同一个全局函数
console.log(this.name);
}
var person1 = new Person2("name6", 6, "hehe");
var person2 = new Person2("name7", 7, "hehe");
console.log(person1.sayName == person2.sayName); // true