Created
August 4, 2015 19:51
-
-
Save jjsub/a56b40517044b2873931 to your computer and use it in GitHub Desktop.
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
The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object). | |
Note: While the syntax of this function is almost identical to that of call(), | |
the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. | |
Examples | |
Using apply to chain constructors | |
You can use apply to chain constructors for an object, similar to Java. In the following example we will create a global Function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. | |
Function.prototype.construct = function (aArgs) { | |
var oNew = Object.create(this.prototype); | |
this.apply(oNew, aArgs); | |
return oNew; | |
}; | |
Note: The Object.create() method used above is relatively new. For an alternative method using closures, please consider the following alternative: | |
Function.prototype.construct = function(aArgs) { | |
var fConstructor = this, fNewConstr = function() { fConstructor.apply(this, aArgs); }; | |
fNewConstr.prototype = fConstructor.prototype; | |
return new fNewConstr(); | |
}; | |
function MyConstructor() { | |
for (var nProp = 0; nProp < arguments.length; nProp++) { | |
this['property' + nProp] = arguments[nProp]; | |
} | |
} | |
var myArray = [4, 'Hello world!', false]; | |
var myInstance = MyConstructor.construct(myArray); | |
console.log(myInstance.property1); // logs 'Hello world!' | |
console.log(myInstance instanceof MyConstructor); // logs 'true' | |
console.log(myInstance.constructor); // logs 'MyConstructor' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment