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

113.手写new操作符 #113

Open
neptoo opened this issue Dec 29, 2019 · 0 comments
Open

113.手写new操作符 #113

neptoo opened this issue Dec 29, 2019 · 0 comments

Comments

@neptoo
Copy link
Owner

neptoo commented Dec 29, 2019

手写一个new操作符

作者:前端劝退师

链接:实现一个new操作符

来源:掘金著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

使用

首先通过例子,看下new的使用

function Animal(name){
  this.name = name;
}
Animal.prototype.sayName = function(){
  console.log('It is ' + this.name);
}
var animal0 = new Animal("dog");
animal0.sayName;
console.log(animal0.name); // dog

可以得出以下结论

  • new 通过构造函数创建出来的实例可以访问到构造函数中的属性
  • new 通过构造函数创建出来的实例可以访问到构造函数原型链中的属性

实现

首先我们再来回顾下 new 操作符的几个作用

  • new 操作符会返回一个对象,所以我们需要在内部创建一个对象
  • 这个对象,也就是构造函数中的 this,可以访问到挂载在 this 上的任意属性
  • 这个对象可以访问到构造函数原型上的属性,所以需要将对象与构造函数链接起来
  • 返回原始值需要忽略,返回对象需要正常处理

回顾了这些作用,我们就可以着手来实现功能了

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

function Animal(name){
  this.name = name;
}
var obj = _new(Animal, 'cat');
// 相当于var obj = new Animal('cat')
console.log(obj.name);  // cat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant