Skip to content

第 14 题:情人节福利题,如何实现一个 new #12

@atheist1

Description

@atheist1

鉴于十三题可以说的东西很多,就先看了十四题,作为一个单身狗,new的对象都是一个小狗啊

// 实现一个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

Activity

zwmmm

zwmmm commented on Feb 14, 2019

@zwmmm

这样写是不是简单点啊

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

atheist1 commented on Feb 14, 2019

@atheist1
Author

@zwmmm 你是对的,我写的有点问题

hwxy

hwxy commented on Feb 15, 2019

@hwxy

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

nnecec

nnecec commented on Feb 18, 2019

@nnecec
function _new(){
  const obj = {}
  const Constructor = Array.prototype.shift.call(arguments)

  obj.__proto__ = Constructor.prototype
  const result = Constructor.apply(obj, arguments)

  return typeof result === 'object' ? result : obj
}
chenjigeng

chenjigeng commented on Feb 18, 2019

@chenjigeng
/**
 *
 *
 * @param {Function} fn
 */
function _new(fn, ...args) {
	const obj = {};
	Object.setPrototypeOf(obj, fn.prototype);
	const result = fn.apply(obj, args);
	// 根据规范,返回 null 和 undefined 不处理,依然返回obj
	return result instanceof Object ? result : obj;
}
ruochuan12

ruochuan12 commented on Feb 18, 2019

@ruochuan12

之前写过一篇模拟实现new的文章~
面试官问:能否模拟实现JSnew操作符

我的这篇文章主要提出了对返回值是函数和对象的处理,还有对new.target的简单处理。

// 去除了注释
function newOperator(ctor){
    if(typeof ctor !== 'function'){
      throw 'newOperator function the first param must be a function';
    }
    newOperator.target = ctor;
    var newObj = Object.create(ctor.prototype);
    var argsArr = [].slice.call(arguments, 1);
    var ctorReturnResult = ctor.apply(newObj, argsArr);
    var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null;
    var isFunction = typeof ctorReturnResult === 'function';
    if(isObject || isFunction){
        return ctorReturnResult;
    }
    return newObj;
}
GuoYuFu123

GuoYuFu123 commented on Feb 19, 2019

@GuoYuFu123

我也贴一个
function Dog(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function Cat(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function _new(fn, ...arg) {
const obj = {};
obj.proto = fn.prototype;
fn.apply(obj, arg)
return Object.prototype.toString.call(obj) == '[object Object]'? obj : {}
}
var dog = _new(Dog,'xxx')
dog.say() //'name = xxx'
console.log(dog instanceof Dog) //true
var cat = _new(Cat, 'carname');
cat.say() //'name = carname'
console.log(cat instanceof Cat) //true

flysme

flysme commented on Feb 19, 2019

@flysme

写的真好

lkoma

lkoma commented on Feb 21, 2019

@lkoma

这样写是不是简单点啊

function  _new(fn,... arg){
     const  obj  =  Object。创造(fn。原型);
    const  ret  =  fn。申请(obj,arg);
    返回 ret instanceof  对象 ?ret  obj;
}

这样ret不是一直都是undefined吗?res instanceof Object就一直是false啊

atheist1

atheist1 commented on Feb 23, 2019

@atheist1
Author

这样写是不是简单点啊

function  _new(fn,... arg){
     const  obj  =  Object。创造(fn。原型);
    const  ret  =  fn。申请(obj,arg);
    返回 ret instanceof  对象 ?ret  obj;
}

这样ret不是一直都是undefined吗?res instanceof Object就一直是false啊

当然不是,这里判断构造函数执行的返回类型,如果构造函数执行结果返回的是个对象不就是true了

zwmmm

zwmmm commented on Feb 25, 2019

@zwmmm

这样写是不是简单点啊

function  _new(fn,... arg){
     const  obj  =  Object。创造(fn。原型);
    const  ret  =  fn。申请(obj,arg);
    返回 ret instanceof  对象 ?ret  obj;
}

这样ret不是一直都是undefined吗?res instanceof Object就一直是false啊

构造函数是默认返回对象的(但是这个是没有返回值的)。但是你也可以自己return一个对象。

Hiker9527

Hiker9527 commented on Apr 2, 2019

@Hiker9527

先理清楚 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;
}
cliYao

cliYao commented on Apr 17, 2019

@cliYao

function _new(fn , ...args){
const obj={}
const Constructor = fn
obj.proto = Constructor.prototype
const result = Constructor.call(obj , ...args)
return typeof result === "object" ? result : obj
}

changed the title [-]14题 情人节快乐![/-] [+]第 14 题:情人节福利题,如何实现一个 new[/+] on Apr 26, 2019

44 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @zuibunan@aeolusheath@calmchang@ke1vin4real@ravencrown

        Issue actions

          第 14 题:情人节福利题,如何实现一个 new · Issue #12 · Advanced-Frontend/Daily-Interview-Question