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

javascript 如何实现一个 new #74

Open
meibin08 opened this issue Feb 6, 2020 · 3 comments
Open

javascript 如何实现一个 new #74

meibin08 opened this issue Feb 6, 2020 · 3 comments

Comments

@meibin08
Copy link
Contributor

meibin08 commented Feb 6, 2020

https://www.javascriptc.com/interview-tips/zh_cn/javascript/javascript-implement-new/

题目描述: 如何实现一个 new

@js-china js-china deleted a comment from meibin08 Feb 6, 2020
@susouth
Copy link
Contributor

susouth commented Apr 9, 2020

  • 思路一:
// 实现一个new
var Dog = function(name) {
  this.name = name
}
Dog.prototype.bark = function() {
  console.log('wangwang')
}
Dog.prototype.sayName = function() {
  console.log('my name is ' + this.name)
}
let sanmao = new Dog('三毛')
sanmao.sayName()
sanmao.bark()
// new 的作用
// 创建一个新对象obj
// 把obj的__proto__指向Dog.prototype 实现继承
// 执行构造函数,传递参数,改变this指向 Dog.call(obj, ...args)
// 最后把obj赋值给sanmao
var _new = function() {
  let constructor = Array.prototype.shift.call(arguments)
  let args = arguments
  const obj = new Object()
  obj.__proto__ = constructor.prototype
  constructor.call(obj, ...args)
  return obj
}
var simao = _new(Dog, 'simao')
simao.bark()
simao.sayName()
console.log(simao instanceof Dog) // true

@susouth
Copy link
Contributor

susouth commented Apr 9, 2020

  • 思路二:
function _new(fn, ...arg) {
	const obj = Object.create(fn.prototype);
	const ret = fn.apply(obj, arg);
	return ret instanceof Object ? ret : obj;
}

@susouth
Copy link
Contributor

susouth commented Apr 9, 2020

思路三:

  • 先理清楚 new 关键字调用函数都的具体过程,那么写出来就很清楚了

  • 1.首先创建一个空的对象,空对象的__proto__属性指向构造函数的原型对象

  • 2.把上面创建的空对象赋值构造函数内部的this,用构造函数内部的方法修改空对象

  • 3.如果构造函数返回一个非基本类型的值,则返回这个值,否则上面创建的对象

function _new(fn, ...arg) {
	var obj = Object.create(fn.prototype);
	const result = fn.apply(obj, ...arg);
	return Object.prototype.toString.call(result) == '[object Object]' ? result : obj;
}

扩展阅读:

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

2 participants