You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function Person (name, age) {
this.name = name;
this.age = age;
this.habit = 'read books';
}
Person.prototype.home = 'Earth';
Person.prototype.sayYourName = function () {
console.log('I am ' + this.name);
}
我们来写一个函数模拟实现new方法
function objectFactory(){
var obj = new Object();
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
Constructor.apply(obj,arguments);
return obj;
}
var person = objectFactory(Person, 'Jack', '18');
function Person (name, age) {
this.strength = 60;
this.age = age;
return {
name: name,
habit: 'Games'
}
}
var person = new Person('Jack', '18');
console.log(person.name) // Jack
console.log(person.age) // undefined
可以看到只能访问返回对象中的属性
构造函数返回基本类型的值
function Person (name, age) {
this.strength = 60;
this.age = age;
return 'i am a person';
}
var person = new Person('Jack', '18');
console.log(person.name) // Jack
console.log(person.age) // 18
这是就和没有返回值的效果一样,person能访问到原型对象和构造函数中的属性。
因此我们要给模拟实现的new方法加上对构造函数返回类型的判断。
function objectFactory(){
var obj = new Object();
Constructor = [].shift.call(arguments);
// obj.__proto__ = Constructor.prototype;
Object.setPrototypeOf(obj, Constructor.prototype);
var result = Constructor.apply(obj,arguments);
// 判断result只能是object类型
return result !== null && typeof result === 'object' ? result : obj;
}
The text was updated successfully, but these errors were encountered:
Uh oh!
There was an error while loading. Please reload this page.
什么是new?
通过new 运算符创建的实例可以拥有构造函数里的属性,同时可以访问到构造函数原型(Function.prototype)中的属性。
假设有这样一个构造函数:
我们来写一个函数模拟实现new方法
构造函数有返回值怎么办
构造函数返回一个对象
可以看到只能访问返回对象中的属性
构造函数返回基本类型的值
这是就和没有返回值的效果一样,person能访问到原型对象和构造函数中的属性。
因此我们要给模拟实现的new方法加上对构造函数返回类型的判断。
The text was updated successfully, but these errors were encountered: