R
R
Rapen2016-10-16 14:52:25
JavaScript
Rapen, 2016-10-16 14:52:25

What is the principle of the function?

And so there is a function that takes one and the second optional argument, the first is a constructor class, the second is its arguments, and in fact it returns its object, there is a question, new (Class.bind.apply( Class, arguments )),
how he receives his prototype, please help in detail)

function construct(Class/*,arg*/) {
 return new (Class.bind.apply( Class, arguments ))()//    ???
}
function Class(name){ 

this.name = name;
}
Class.prototype.sayHello = function(){
  
  return 'Hello' + ' ' +  this.name;
  
}
var obj = construct(Class, 'Steve');

console.log(obj.name); // "Steve"
console.log(obj.sayHello()); // "Hello Steve"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Mudrenok, 2016-10-16
@mudrenokanton

In fact, this whole crutch is no different from:

function construct(Class, name) {
  return new Class(name);
}

But the author became a hostage to a completely stupid idea to write a construct function that would take a non-hardcoded argument. Therefore, he took the Class function and called its bind () method through call (), in order not to list the arguments separated by commas, but simply specify them as an array. This bind function returned the body of the function, which was then called as a constructor with new

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question