Skip to content
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

JS 中 new 一个对象时的二三事 #27

Open
jyzwf opened this issue Oct 24, 2017 · 0 comments
Open

JS 中 new 一个对象时的二三事 #27

jyzwf opened this issue Oct 24, 2017 · 0 comments

Comments

@jyzwf
Copy link
Owner

jyzwf commented Oct 24, 2017

    var Person = function(name){
        this.name = name;
    }

    Person.prototype.getName = function(){
        return this.name;
    }

   var Bob = new Person('Bob');    // 这里 new Person('Bob') 发生了什么?

下面我们来探探:
当代码 new Person('Bob') 执行时:

  1. 创建一个新的对象 { },这个对象的类型是 object;
  2. 设置这个新对象的 [[prototype]](i.e proto )属性为构造函数的原型对象;
  3. 绑定构造函数的 this 关键字指向这个新对象,执行构造函数;
  4. 如果构造函数有返回值,就直接返回这个值;否则返回新创建的对象(除非构造方法中返回的是‘无原型’)。
  5. 在创建新对象成功之后,如果调用一个新对象没有的属性的时候,JavaScript 会延原型链向止逐层查找对应的内容

代码模拟

  function New(func) {
    var res = {};
    if (func.prototype !== null) {
        res.__proto__ = func.prototype;
    }
    var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
    if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {    // typeof null === 'object'
        return ret;
    }
    return res;
}

最后附上一张原型链的图:
image

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