Object.create
STEP 1: What is the difference between new & Object.create???
ANSWER PART 1: The NEW Operator Does 4 Things:
1 - It creates a new object.
2 - It sets this new object’s internal [[prototype]] property to be the constructor function’s external, accessible, prototype object (every function object automatically has a prototype property that is itself an object).
3 - It executes the constructor function, using the newly created object whenever this is mentioned (in order to pass on the own properties of the constructor function to the newly created object). In other words, the newly constructed object is set as the this binding for that function call.
4 - It returns the newly created object, unless the constructor function returns a non-primitive value (i.e. unless it returns its own alternate object). In this case, that non-primitive value will be returned.
ANSWER PART 2: Object.create
The Object.create() Method Does 3 Things:
1 - It creates a new object. The Object.create() method takes one required argument: the object that should be the prototype of the newly-created object. The second, optional argument is an object that sets properties typically fed to Object.defineProperties().
2 - It sets this new object’s internal [[prototype]] property to be the constructor function’s external, accessible, prototype object (every function object automatically has a prototype property that is itself an object). An object’s internal [[prototype]] property creates the linkage by which method retrieval via the prototype chain occurs.
3 - It returns the newly created object, unless the constructor function returns a non-primitive value (i.e. unless it returns its own alternate object). In this case, that non-primitive value will be returned.
ANSWER PART 3: The Difference
Unlike the new operator, Object.create() does not execute a constructor function with the newly created object (thereby giving it own properties).
STEP 2: CODE OBJECT.CREATE
SOLUTION:
if (!Object.create){
Object.create = function(obj){
//create a throwaway F function
function F() {}
//override the prototype property that each function receives upon declaration
//and point the prototype property to the obj we want to link it to
F.prototype = obj;
//use the new F() construction to make a new object that will be linked as specified
// it does not run the passed in object through own properties
return new F();
};
}
BETTER SOLUTION:
if (typeof Object.create != 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
Object.create
By ayana28
Object.create
- 1,593