Last active
December 30, 2015 13:09
-
-
Save forivall/7833920 to your computer and use it in GitHub Desktop.
The `new` function from "Crockford on JavaScript - Chapter 2" -- https://www.youtube.com/watch?v=RO1Wnu-xKoY&list=PL7664379246A246CB#t=30m12s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// > JavaScript itself was confused about its prototypal nature. Originally it | |
// > didn't have `Object.create`; instead it had the new operator which modified | |
// > the way invocation worked. If you were to express the new operator as a new | |
// > function, this is what it actually does: it calls Object.create on the | |
// > prototype property of your function, makes a new object that inherits from | |
// > that, and then it calls your function, binding the new object to that and | |
// > passing along whatever arguments you gave it. Then it takes the result, and | |
// > if the result is an object then it returns that object, and if it's not an | |
// > object, then it returns the object that you made. It was trying to look | |
// > classical so that the Java kids would loook at it and go yeah, OK, this | |
// > isn't too different. But it doesn't look classical at all, particularly | |
// > when you look at how you put methods into a class, or a pseudo-class, where | |
// > you go to func.prototype and then start sticking stuff on it. It is really | |
// > ugly. And then if you want to inherit from something, it is even worse. So | |
// > I don't use new anymore. I don't need it. I'm thinking prototypally now, | |
// > and when I'm thinking prototypally I can do everything I want to do with | |
// > object.create. So I see this now as just a vestige; I don't need it | |
// > anymore. There is also hazard with new, that if you design a constructor | |
// > that is supposed to be used with new and either you, or one of your users, | |
// > forgets to put the new prefix on it, instead of initializing a new object | |
// > ... . That's a feature I don't need to use. | |
function new_(func, args) { | |
var that = Object.create(func.prototype), | |
result = func.apply(that, args); | |
return (typeof result === 'object' && result) || that; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment