Using apply() in IIFE - javascript

I'm trying to use apply() within IIFE. I get an error 'intermediate value is not a function' where am I going wrong ?
var Person = {
getFullName : function(firstName, lastName) {
return firstName + ' ' + lastName;
}
}
/* IIFE - using apply */
(function(firstName, lastName) {
getName = function(){
console.log("From IIFE..");
console.log(this.getFullName(firstName, lastName));
}
getName();
}).apply(Person, ['John', 'Doe']);
Plnnkr : http://plnkr.co/edit/77db8Mu4i9RXGqt26PAP?p=preview

The problem is with ;, in your code the Person object syntax is not terminated, and the IIFE is considered as continuation of that.
Read: Automatic semicolon insertion
If you look at external libraries, their IIFE statement starts with a ;, that is used to escape from this scenario.
Also note that, inside your getName function this does not refer to the Person object, you need to either use a closure variable or pass the value for this manually.
var Person = {
getFullName: function(firstName, lastName) {
return firstName + ' ' + lastName;
}
}
/* IIFE - using apply */
;
(function(firstName, lastName) {
var self = this;
var getName = function() {
console.log("From IIFE..");
console.log(self.getFullName(firstName, lastName));
}
getName();
}).apply(Person, ['John', 'Doe']);

Related

Can a function be declared as a variable in JavaScript?

Consider the following JavaScript object definition :
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
I know that if we want to use the object property(i.e. a function) we have to write the following code :
person.fullName();
As per my knowledge, JavaScript objects are containers for named values called properties or methods.
Also, I know that I can define the object properties like firstName, lastName, id as individual variables.
Now, my question is can I also define the function "fullName" as a variable? If it is possible then how? and if not then why?
Thank You.
It is possible. Note that your code is equivalent to this code:
var person = {};
person.firstName = "John";
person.lastName = "Doe";
person.id = 5566;
person.fullName = function() {
return this.firstName + " " + this.lastName;
}
The important bit to see is that function() { return this.firstName + " " + this.lastName; } (or rather, the result of evaluation of that string of code) is a value, just like 5566 is, and can be contained in a property, or a variable, or an array... just like 5566 can. The only difference is, one is a number, the other - a function.
Besides the original example of a function stored in a property ("method"), here is an example of a functional value being stored in a variable:
var sayHello = function(name) { console.log("Hello, " + name); }
Here it is in an array:
var adders = [
function(x) { return a; },
function(x) { return (a + 1) % 3; }
function(x) { return (a + 2) % 3; }
];
Here it is being passed as a parameter:
function twice(f, x) {
return f(f(x));
}
twice(function(x) { return x * 2; }, 7);
// 28
Yes
Here is simple answer with example to your question
jQuery(document).ready(function() {
window.$ = jQuery;
initializeGlobelCalls.init();
});
var initializeGlobelCalls = function () {
var validatefunction = function() {
$(document).on('click','#divid',function(){//event trigger when you want to call function
//your function code
});
};
return {
init: function () {
validatefuction();//can add multiple functions here
}
};
}();
with this structure you can write multiple functions ,first need to define function like validatefunction and then add into init
It is not possible unless you generate fullName when creating the object such as the following:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : ''
};
person.fullName = person.firstName + person.lastName;
Otherwise there's no way to create a static variable only one that will be created by the function when called (such as in your original example).
That is not possible because by the way JavaScript was designed, you can't have dynamic properties assigned statically (apart from ES6 getters as cited below, which will still generate the value on every call) in a way that they'll only be generated once automatically without some kind of algorithm from your part or a library to do that for you.
As I cited above, you can try ES6 getters but that will only make it look like a property, it will still get called every time it is accessed:
Example:
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
get fullName() { return this.firstName + ' ' + this.lastName; }
};
Then you'd access it like this: person.fullName
In JavaScript a variable can point to function as well.
Example:
var fullName = function(param) {
return param;
}
console. log(fullName('some text'));

Why doesn't typescript use the 'self' trick?

I wrote the following TypeScript code:
class Person {
constructor(public firstname: string, public lastname:string){
}
public die(){
this.lastname += " RIP";
}
And this compiles to:
var Person = (function() {
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
Person.prototype.die = function () {
this.lastname += " RIP";
};
return Person;
})();
Which of course is a valid way, but it will not work as expected in the following case:
function run(delegate){
delegate();
}
var person = new Person("guy", "dude");
run(person.die);
alert(person.lastname);
alert(lastname);
The expected alerts here would be "dude RIP", and then "undefined". However, the actual result would be "dude" and "undefined RIP". This is because the this parameter works strangely in JS.
A common solution to that is to use a self variable by closure, and to abandon the prototype mechanism, i.e.
var Person = (function() {
function Person(firstname, lastname) {
var self = this;
self.firstname = firstname;
self.lastname = lastname;
self.die = function() {
self.lastname += " RIP";
}
}
return Person;
})();
Which would work as expected.
What is advantage of that specific way to compile code? Did typescript decide to leave that piece of unintuitive code?
You should use the arrow function syntax when you want to capture this. I think it would be better to use this at the sight of delegate creation instead of class creation.
The only change needed would be:
run(()=>person.die());
This allows you to capture this for any function regardless of how it was defined.
You need to change the structure of your code slightly to get it to use the _this = this pattern:
class Person {
constructor(public firstName: String, public lastName: String) {
}
die = () => {
this.lastName += "dead"
}
}
Becomes:
var Person = (function () {
function Person(firstName, lastName) {
var _this = this;
this.firstName = firstName;
this.lastName = lastName;
this.die = function () {
_this.lastName += "dead";
};
}
return Person;
})();
The key part is that you need to place the die function on the object not the prototype, which forces it to use _this = this.
Because that is how classes in JS works. Typescript devs decided they didn't want to change any pre existing features of the lang.

Javascript revealing module pattern and variables

My question is precisely the same as this one Javascript revealing module pattern, public properties
In that thread, the answer was given but not the "why". Here's the same question restated with my own example:
myApp.User = function () {
var firstName = 'Default',
lastName = 'Default';
function setFirstName(name) {
firstName = name;
}
function setLastName(name) {
lastName = name;
}
function getFirstName() {
return firstName;
}
function getLastName() {
return lastName;
}
return {
getLastName: getLastName,
**getFirstName: getFirstName**,
setLastName: setLastName,
setFirstName: firstName
};
};
In this scenario, User().getFirstName always evals to "Default" -- even if I change it to some other value via the setFirstName function.
If I replace with setFirstName like:
return {
getLastName: getLastName,
**getFirstName: getFirstName**,
setLastName: setLastName,
setFirstName: firstName
};
I am able to access the changed value. I understand that the var firstName is passed by value which is why the updated values are not reflected. I don't understand what is special about the function. Where is the pointer to the value within the function living? Why do all the functions "magically" get access to the update(s)?
Where is the pointer to the value within the function living?
In the scope of the function - which contains all the variables it has access to. This access makes the function a closure actually.
Why do all the functions "magically" get access to the update(s)?
Because all the functions share the variables declared in a higher scope.
They don't "magically" get access to the update. They are inside myApp.User that's why they can access the variable location.
When you do myApp.User().getFirstName(), because getFirstName is inside the function (scope), it will be able to access variables declared both inside this function and outside this function.
function a(){
var b = "hello";
return {
setB: function(c){ b = c; },
getB: function(){ return b; }
};
}
var obj = new a();
obj.getB(); //hello
obj.setB("new");
obj.getB(); //new
In the example above, getB and setB both live inside your object, and they can access all variables inside the a() scope.
look at what you did here in your first example
setFirstName: firstName
setFirstName is not a reference to the function "setFirstName" but rather the variable 'firstName'... you don't have access to the function 'setFirstName'. That function is still unavailable to you, so you can't modify firstName, like you want.
It is out of scope - you didn't return it, so that it is available to the outside world, so to speak. It is not available "outside" of the scope of the function. Return the function (), and apply the "setFirstName", as shown below.
try this;
myApp.User = function () {
var firstName = 'Default',
lastName = 'Default';
function setFirstName(name) {
firstName = name;
}
function setLastName(name) {
lastName = name;
}
function getFirstName() {
return firstName;
}
function getLastName() {
return lastName;
}
return {
getLastName: getLastName,
getFirstName: getFirstName,
setLastName: setLastName,
setFirstName: setFirstName
};
}();
myApp.User.setFirstName('bill');
myApp.User.getFirstName();
var User = function () {
var firstName = 'Default',
lastName = 'Default';
return {
getLastName: function() { return lastName; },
getFirstName: function() { return firstName; },
setLastName: function(name) { lastName = name; },
setFirstName: function(name) { firstName = name; },
getName: function() { return firstName + ' ' + lastName; }
};
};
var u = User(),
v = User();
console.log( u.getName() + ' - ' + v.getName() );
// Outputs: 'Default Default - Default Default'
u.setFirstName( 'Alice' );
u.setLastName( 'Bob' );
console.log( u.getName() + ' - ' + v.getName() );
// Outputs: 'Alice Bob - Default Default'

JavaScript calls to methods from within constructors

I was reading the re-introduction to JavaScript on MDN website and came across this in the Custom Objects section:
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
It says on the MDN website that you can make a reference to the personFullName() and personFullNameReversed() functions from within the Person constructor simply by typing in their names and assigning them as values to the two variables stated in the code above (this.fullName and this.fullNameReversed). This is all very clear to me, but my question is why are the brackets next to personFullName and personFullNameReversed omitted? Shouldn't it say:
this.fullName = personFullName();
this.fullNameReversed = personFullNameReversed();?
The way that it was presented in the example from the MDN website I feel like those fullName and fullNameReversed properties from the Person constructor are pointing to some already declared global variables instead of functions declared outside of the Person constructor.
If you add the brackets, you'll call the functions and assign their return values to this.fullName and this.fullNameReversed.
The code is referring to the functions, not calling them.
It's assigning the function, not the result of the function. It's equivalent to:
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = function () {
return this.first + ' ' + this.last;
};
this.fullNameReversed = function () {
return this.last + ', ' + this.first;
};
}
so now you can do:
var jack = new Person('Jack', 'Smith');
console.log(jack.fullName()); // Jack Smith

What is the difference between these three module pattern implementations in JavaScript?

I've seen the following three code blocks as examples of the JavaScript module pattern. What are the differences, and why would I choose one pattern over the other?
Pattern 1
function Person(firstName, lastName) {
var firstName = firstName;
var lastName = lastName;
this.fullName = function () {
return firstName + ' ' + lastName;
};
this.changeFirstName = function (name) {
firstName = name;
};
};
var jordan = new Person('Jordan', 'Parmer');
Pattern 2
function person (firstName, lastName) {
return {
fullName: function () {
return firstName + ' ' + lastName;
},
changeFirstName: function (name) {
firstName = name;
}
};
};
var jordan = person('Jordan', 'Parmer');
Pattern 3
var person_factory = (function () {
var firstName = '';
var lastName = '';
var module = function() {
return {
set_firstName: function (name) {
firstName = name;
},
set_lastName: function (name) {
lastName = name;
},
fullName: function () {
return firstName + ' ' + lastName;
}
};
};
return module;
})();
var jordan = person_factory();
From what I can tell, the JavaScript community generally seems to side with pattern 3 being the best. How is it any different from the first two? It seems to me all three patterns can be used to encapsulate variables and functions.
NOTE: This post doesn't actually answer the question, and I don't consider it a duplicate.
I don't consider them module patterns but more object instantiation patterns. Personally I wouldn't recommend any of your examples. Mainly because I think reassigning function arguments for anything else but method overloading is not good. Lets circle back and look at the two ways you can create Objects in JavaScript:
Protoypes and the new operator
This is the most common way to create Objects in JavaScript. It closely relates to Pattern 1 but attaches the function to the object prototype instead of creating a new one every time:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
Person.prototype.changeFirstName = function (name) {
this.firstName = name;
};
var jordan = new Person('Jordan', 'Parmer');
jordan.changeFirstName('John');
Object.create and factory function
ECMAScript 5 introduced Object.create which allows a different way of instantiating Objects. Instead of using the new operator you use Object.create(obj) to set the Prototype.
var Person = {
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
}
var jordan = Object.create(Person);
jordan.firstName = 'Jordan';
jordan.lastName = 'Parmer';
jordan.changeFirstName('John');
As you can see, you will have to assign your properties manually. This is why it makes sense to create a factory function that does the initial property assignment for you:
function createPerson(firstName, lastName) {
var instance = Object.create(Person);
instance.firstName = firstName;
instance.lastName = lastName;
return instance;
}
var jordan = createPerson('Jordan', 'Parmer');
As always with things like this I have to refer to Understanding JavaScript OOP which is one of the best articles on JavaScript object oriented programming.
I also want to point out my own little library called UberProto that I created after researching inheritance mechanisms in JavaScript. It provides the Object.create semantics as a more convenient wrapper:
var Person = Proto.extend({
init : function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
},
fullName : function () {
return this.firstName + ' ' + this.lastName;
},
changeFirstName : function (name) {
this.firstName = name;
}
});
var jordan = Person.create('Jordan', 'Parmer');
In the end it is not really about what "the community" seems to favour but more about understanding what the language provides to achieve a certain task (in your case creating new obejcts). From there you can decide a lot better which way you prefer.
Module patterns
It seems as if there is some confusion with module patterns and object creation. Even if it looks similar, it has different responsibilities. Since JavaScript only has function scope modules are used to encapsulate functionality (and not accidentally create global variables or name clashes etc.). The most common way is to wrap your functionality in a self-executing function:
(function(window, undefined) {
})(this);
Since it is just a function you might as well return something (your API) in the end
var Person = (function(window, undefined) {
var MyPerson = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
MyPerson.prototype.fullName = function () {
return this.firstName + ' ' + this.lastName;
};
MyPerson.prototype.changeFirstName = function (name) {
this.firstName = name;
};
return MyPerson;
})(this);
That's pretty much modules in JS are. They introduce a wrapping function (which is equivalent to a new scope in JavaScript) and (optionally) return an object which is the modules API.
First, as #Daff already mentioned, these are not all module patterns. Let's look at the differences:
Pattern 1 vs Pattern 2
You might omit the useless lines
var firstName = firstName;
var lastName = lastName;
from pattern 1. Function arguments are already local-scoped variables, as you can see in your pattern-2-code.
Obviously, the functions are very similar. Both create a closure over those two local variables, to which only the (exposed) fullName and the changeFirstName functions have access to. The difference is what happens on instantiation.
In pattern 2, you just return an object (literal), which inherits from Object.prototype.
In pattern 1, you use the new keyword with a function that is called a "constructor" (and also properly capitalized). This will create an object that inherits from Person.prototype, where you could place other methods or default properties which all instances will share.
There are other variations of constructor patterns. They might favor [public] properties on the objects, and put all methods on the prototype - you can mix such. See this answer for how emulating class-based inheritance works.
When to use what? The prototype pattern is usually preferred, especially if you might want to extend the functionality of all Person instances - maybe not even from the same module. Of course there are use cases of pattern 1, too, especially for singletons that don't need inheritance.
Pattern 3
…is now actually the module pattern, using a closure for creating static, private variables. What you export from the closure is actually irrelevant, it could be any fabric/constructor/object literal - still being a "module pattern".
Of course the closure in your pattern 2 could be considered to use a "module pattern", but it's purpose is creating an instance so I'd not use this term. Better examples would be the Revealing Prototype Pattern or anything that extends already existing object, using the Module Pattern's closure - focusing on code modularization.
In your case the module exports a constructor function that returns an object to access the static variables. Playing with it, you could do
var jordan = person_factory();
jordan.set_firstname("Jordan");
var pete = person_factory();
pete.set_firstname("Pete");
var guyFawkes = person_factory();
guyFawkes.set_lastname("Fawkes");
console.log(jordan.fullname()); // "Pete Fawkes"
Not sure if this was expected. If so, the extra constructor to get the accessor functions seems a bit useless to me.
"Which is best?" isn't really a valid question, here.
They all do different things, come with different trade-offs, and offer different benefits.
The use of one or the other or all three (or none) comes down to how you choose to engineer your programs.
Pattern #1 is JS' traditional take on "classes".
It allows for prototyping, which should really not be confused with inheritance in C-like languages.
Prototyping is more like public static properties/methods in other languages.
Prototyped methods also have NO ACCESS TO INSTANCE VARIABLES (ie: variables which aren't attached to this).
var MyClass = function (args) { this.thing = args; };
MyClass.prototype.static_public_property = "that";
MyClass.prototype.static_public_method = function () { console.log(this.thing); };
var myInstance = new MyClass("bob");
myInstance.static_public_method();
Pattern #2 creates a single instance of a single object, with no implicit inheritance.
var MyConstructor = function (args) {
var private_property = 123,
private_method = function () { return private_property; },
public_interface = {
public_method : function () { return private_method(); },
public_property : 456
};
return public_interface;
};
var myInstance = MyConstructor(789);
No inheritance, and every instance gets a NEW COPY of each function/variable.
This is quite doable, if you're dealing with objects which aren't going to have hundreds of thousands of instances per page.
Pattern #3 is like Pattern #2, except that you're building a Constructor and can include the equivalent of private static methods (you must pass in arguments, 100% of the time, and you must collect return statements, if the function is intended to return a value, rather than directly-modifying an object or an array, as these props/methods have no access to the instance-level data/functionality, despite the fact that the instance-constructor has access to all of the "static" functionality).
The practical benefit here is a lower memory-footprint, as each instance has a reference to these functions, rather than their own copy of them.
var PrivateStaticConstructor = function (private_static_args) {
var private_static_props = private_static_args,
private_static_method = function (args) { return doStuff(args); },
constructor_function = function (private_args) {
var private_props = private_args,
private_method = function (args) { return private_static_method(args); },
public_prop = 123,
public_method = function (args) { return private_method(args); },
public_interface = {
public_prop : public_prop,
public_method : public_method
};
return public_interface;
};
return constructor_function;
};
var InstanceConstructor = PrivateStaticConstructor(123),
myInstance = InstanceConstructor(456);
These are all doing very different things.

Categories

Resources