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

第 5 题:new操作符都做了什么 #5

Open
airuikun opened this issue Apr 8, 2019 · 7 comments
Open

第 5 题:new操作符都做了什么 #5

airuikun opened this issue Apr 8, 2019 · 7 comments

Comments

@airuikun
Copy link
Owner

airuikun commented Apr 8, 2019

四大步骤:

1、创建一个空对象,并且 this 变量引用该对象,// lat target = {};

2、继承了函数的原型。// target.proto = func.prototype;

3、属性和方法被加入到 this 引用的对象中。并执行了该函数func// func.call(target);

4、新创建的对象由 this 所引用,并且最后隐式的返回 this 。// 如果func.call(target)返回的res是个对象或者function 就返回它

function new(func) {
	lat target = {};
	target.__proto__ = func.prototype;
	let res = func.call(target);
	if (typeof(res) == "object" || typeof(res) == "function") {
		return res;
	}
	return target;
}
@IGSWL
Copy link

IGSWL commented Apr 9, 2019

lat 是什么声明?

@scTaoFelix
Copy link

lat是什么声明?

写错了,let

@radicalviva
Copy link

上述说的还是 ES5 时的实现方式

@JayZangwill
Copy link

if (typeof(res) == "object" && res || typeof(res) == "function") {
    return res;
}

这里别忘了 typeof null == 'object' 的情况

@xiaoheng21
Copy link

@haoHu
Copy link

haoHu commented Feb 24, 2020

function newFactory(func) {
  if (typeof func !== 'function') {
    throw '第一个参数必须是构造函数';
  }
  // ES6 new.target 指向构造函数
  newFactory.target = func;
  // 以构造器的prototype属性为原型,创建新对象
  let newObj = Object.create(func.prototype);
  // 其余参数
  let args = [].slice.call(arguments, 1);
  // 将this和调用参数传给构造器执行
  let result = func.apply(newObj, args);
  // 结果是Object和Function类型的可以返回,这里要排除null,因为它也是’object'
  let isObject = typeof result === 'object' && result !== null;
  let isFunction = typeof result === 'function';
  if(isObject || isFunction) {
    return result;
  }
  // 返回新建的对象实例
  return newObj;
}

@qwekelly
Copy link

function myNew(func, ...ages) {
let target = {};
target.proto = func.prototype;
let res = func.call(target, ...ages);
if (typeof(res) == "object" || typeof(res) == "function") {
return res;
}
return target;
}

function Person (name, age) {
this.name = name
this.age = age
}

调用:myNew(Person, 'qq', 12)

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

8 participants