8000 js 模拟实现new · Issue #8 · Vxee/articles · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

js 模拟实现new #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Vxee opened this issue Jul 1, 2018 · 0 comments
Open

js 模拟实现new #8

Vxee opened this issue Jul 1, 2018 · 0 comments

Comments

@Vxee
Copy link
Owner
Vxee commented Jul 1, 2018

什么是new?

new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一

通过new 运算符创建的实例可以拥有构造函数里的属性,同时可以访问到构造函数原型(Function.prototype)中的属性。

假设有这样一个构造函数:

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');
  1. 创建了一个空对象obj
  2. 通过shift方法将arguments的第一个参数即传入的构造函数移除并返回给Constructor这个变量
  3. 设置obj的原型指向构造函数的原型,这个obj就能访问构造函数原型中的属性。
  4. 使用apply,改变构造函数的this为obj,这样obj就可以拥有构造函数的一些属性。
  5. 返回obj

构造函数有返回值怎么办

构造函数返回一个对象
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0