简体   繁体   中英

What does undefined refer to in javascript function prototype

In this code what does undefined mean? Without specifying undefined it says " my name is undefined and i am a undefined"

 (function(){ 'use strict'; function theFunction(name, profession) { console.log("My name is " + name + " and I am a " + profession + " . "); } theFunction("John", "fireman"); theFunction.apply(undefined,["ali", "Developer"]); theFunction.call(undefined, "sara", "doctor"); }()); 

My answer assumes that by Without specifying undefined you mean a call like that:

 theFunction.apply(["ali", "Developer"]);

When you use call or apply , the first parameter is the execution context (variable this inside theFunction ). The two examples set it to undefined , so this inside theFunction will evaluate to undefined . For example:

function theFunction(name, profession) {
      console.log(this); // logs `undefined`
      console.log("My name is " + name + " and I am a " + profession + " . ");
}

theFunction.apply(undefined, ["ali", "Developer"]);

Here is the thread explaining why one would use undefined as execution context.

Now, to your question. If you omit undefined in your call is like that:

theFunction.apply(["ali", "Developer"]);

the execution context - this - is set to ["ali", "Developer"] , and name and profession are evaluated as undefined since you only pass one parameter to apply , that is why you're getting "My name is undefined and I am a undefined"

call and apply are usually used when you want to change the execution context of the function. You're probably using apply to turn array of arguments into separate arguments. To do that, you need to set the same execution context as the one that would have been if you called the function without apply:

theFunction("John", "fireman"); // `this` points to `window`
theFunction.apply(this, ["John", "fireman"]); // `this` points to `window`

Though theFunction() is not included as one of the calls tried, theFunction() reproduces result described at Question

Without specifying undefined it says " my name is undefined and i am a undefined"

that is, to call theFunction() without passing parameters; which would be expected result where name and profession are undefined within function body when theFunction is called.

 (function() { 'use strict'; function theFunction(name, profession) { console.log("My name is " + name + " and I am a " + profession + " . "); } theFunction(); // logs result described at Question theFunction("John", "fireman"); theFunction.apply(undefined, ["ali", "Developer"]); theFunction.call(undefined, "sara", "doctor"); }()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM