![]() I was almost certain that this approach would fail given the fact that we aren't using the "new" keyword as a means to create a new context. To be honest, I'm a bit surprised that this worked. And, when we run the above code, we get the following console output: Var message = createString( "Boom shaka laka!" ) Ĭonsole.log( ( message ) ) Īs you can see, both the Array and String proxy methods simply pass "null" in as the first argument to the apply() method call. Var friends = createArray( "Sarah", "Tricia", "Joanna" ) Ĭonsole.log( ( friends ) ) Var newString = String.apply( null, arguments ) When doing this, the new string is returned A proxy to the native String constructor. Var newArray = Array.apply( null, arguments ) When doing this, the new array is returned Invoke the native constructor, passing in any given A proxy to the native Array constructor. Invoking A Native JavaScript Constructor With Apply() As such, I simply tried to pass "null" to the apply() method: When dealing with a native JavaScript constructor function, I didn't have a pre-existing variable to use as the "this" context. Using call() and apply(), however, we can explicitly define a new reference for "this" no matter where the target method resides. Typically, when a function is invoked, any embedded reference to "this" is implicitly a reference to the object on which the method was invoked. That is, they allow us to change the "this" reference used within the body of a given function invocation. When invoking a native JavaScript constructor, on the other hand, I had no existing sub-class instance so, would this even be possible?Īs a quick recap, JavaScript's call() and apply() methods allow us to change the execution context of a given function. But, in those cases, I had existing sub-class instances that would act as the target context (ie. In the past, I've often invoked super-class constructors using JavaScript's call() or apply() method. This morning, I was working on some JavaScript code in which I wanted to create a proxy to a native JavaScript constructor (ex.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |