// Otaku 御宅族,简称宅
function Otaku (name, age) {
this.name = name;
this.age = age;
this.habit = 'Games';
}
// 因为缺乏锻炼的缘故,身体强度让人担忧
Otaku.prototype.strength = 60;
Otaku.prototype.sayYourName = function () {
console.log('I am ' + this.name);
}
var person = new Otaku('Kevin', '18');
console.log(person.name) // Kevin
console.log(person.habit) // Games
console.log(person.strength) // 60
person.sayYourName(); // I am Kevin
从这个例子中,我们可以看到,实例 person 可以:
访问到 Otaku 构造函数里的属性
访问到 Otaku.prototype 中的属性
模拟思路
new 返回是一个Object
需要设置__proto__指向
模拟实现
第一版
// 第一版代码
function objectFactory() {
var obj = new Object(),
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
Constructor.apply(obj, arguments);
return obj;
};