Javascript Properties - javascript

Please let me know if question is just dumb and not answerable?
I've just started unit testing with javascript. I have been implementing this blog code into my app. I just confused with name argument being passed to function in javascript. If we talk about Java,Php or any other language they take arguments in construct function and is understandable to use within class something like
$vehicle = new Vehicle('argument here');
Class Vehicle {
protected $name;
function __construct($name) {
$this->name = $name; // we can use the property any where in the class
}
}
//Is name Property? Object? or anything else?
//javascript
(function(name) {
"use strict";
function vehicle(modal) {
this.modal = modal || 'Civic 2015';
}
name.vehicle = vehicle; //? ? ?
})(this);//also why using (this) ?
Also an example would be greatly welcomed.

Javascript doesn't have class (really) and so OOP is handled slightly differently to some of the languages you mention. Often you'll see something like this:
function Vehicle(make, color){
this.make = make;
this.color = color;
}
Vehicle.prototype.getMake = function(){
return this.make;
}
var myCar = new Vehicle('ford', 'green');
myCar.getMake(); //'ford'
As shown in this fiddle I made: https://jsfiddle.net/eqf2apwx/
There are many ways to handle JS objects, however, and I'd suggest you google it a bit, particularly 'Crockford Classless' which is a popular way of handling objects.

The function that you are using above is called self-executing immediate functions, "this" inside such functions always points to the global object, because inside functions that were invoked as functions (that is, not as constructors with new) "this" should always point to the global object.
This pattern is useful because it provides a scope sandbox for your initialization code. Think about the following common scenario: Your code has to perform some setup tasks when the page loads, such as attaching event handlers, creating objects, and so on. All this work needs to be done only once, so there’s no reason to create a reusable named function. But the code also requires some temporary variables, which you won’t
need after the initialization phase is complete. It would be a bad idea to create all those variables as globals. That’s why you need an immediate function—to wrap all your code in its local scope and not leak any variables in the global scope
However, in ECMAScript 5 in strict mode, "this" reference doesn't necessarily point to the global object so you have to adopt a different pattern when your code is in strict mode. Therefore, developers usually pass the reference to "this" from the global scope. SO in your case "this" which is passed as an argument to immediate function is a reference to the global "window" object. Also, this pattern makes the code more interoperable in environments outside the browser because you don't need to hardcode "window" inside the immediate function.

Related

javascript closure advantages?

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.
Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible.
The advantage of closures in javascript is that it allows you to bind a variable to an execution context.
var closedIn = {};
var f = function(){
closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}
in that example, you have a normal object literal called closedIn. It is accessed in a function. Because of that, javascript knows it has to bring closedIn everywhere it brings the function f, so it is available to f.
The this keyword is tricky. this is always a reference to the execution scope. You can capture the this of one context to use in another context as follows:
var that = this;
var f = function(){
that.somethingOnThat();
// `this` means the scope f, `that` means whatever 'this' was when defined outside of the function
}
This trick can be very useful somethings, if you are coding object oriented javascript and want a callback to have access to some external scope.
To quote from a Javascript book:
"Functions in JavaScript are lexically
rather than dynamically scoped. This
means that they run in the scope in
which they are defined, not the scopee
from which they are executed. When a
function is defined, the current scope
chain is saved and becomes part of the
internal state of the function."
So the clear advantage is that you can bring any object (functions, objects, etc) along with the scope chain as far as is necessary. This is can also be considered a risk, because your apps can easily consume lots of memory if you are not careful.
I think the best phrase to sum up the purpose of closures would be:
Data Encapsulation
With a function closure you can store data in a separate scope, and share it only where necessary.
If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:
(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}());
Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.
I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.
As we know, the variables that are defined in functions, have local scope. We can't access them from outside of the function.
Problem 1:
local variables are created when the function is called and they will be destroyed when the function's task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.
Global variables are available when the program starts and are destroyed when it ends. They are also available throughout the program.
Problem 2:
Since global variables are accessible throughout the program, they are prone to change from everywhere.
What do we want?
We want to have data persistency + data encapsulation.
We can achieve them by using Closures. By using a closure we can have private variables that are available even after a function's task is finished.
Example:
function initCounter() {
let counter = 0;
return function () {
return ++counter;
}
}
// Each counter is persistent
const countJumps = initCounter();
countJumps();
countJumps();
alert("Jumps count is: " + countJumps());
const countClicks = initCounter();
countClicks();
countClicks();
countClicks();
countClicks();
alert("Clicks count is: " + countClicks());
// Each counter is isolated
alert(counter); // Error: counter is not defined

Is it good to write javascript functions inside functions and not use 'new' on the main function?

I now know this works:
function outerfunction(arg1, arg2, arg3) {
var others;
//Some code
innerFunction();
function innerFunction() {
//do some stuff
//I have access to the args and vars of the outerFunction also I can limit the scope of vars in the innerFunction..!
}
//Also
$.ajax({
success : secondInnerFunction;
});
function secondInnerFunction() {
// Has all the same benefits!
}
}
outerFunction();
So, I am not doing a 'new' on the outerFunction, but I am using it as an object! How correct is this, semantically?
There doesn't appear to be anything wrong with what you're doing. new is used to construct a new object from a function that is intended as a constructor function. Without new, no object is created; the function just executes and returns the result.
I assume you're confused about the closure, and how the functions and other variables belonging to the function scope are kept alive after the function exits. If that's the case, I suggest you take a look at the jibbering JavaScript FAQ.
You are not using the outer function as an object. You are using it to provide a closure. The border line is, admittedly, thin, but in this case, you are far away from objects, since you do not pass around any kind of handle to some more generic code invoking methods, all you do is limiting the scope of some variables to the code that needs to be able to see them.
JFTR, there is really no need to give the outer function a name. Just invoke it:
(function() { // just for variable scoping
var others;
...
})()
I do this sort of thing all the time. Yes - javascript blurs the boundary between objects and functions somewhat. Or perhaps, more correctly, a javascript function is just an object that is callable. You would only really use the 'new' prefix if you wanted to have multiple instances of the function. My only suggestion here is that its usually considered good practice to call a function after you've declared it (you are calling the innerFunction before it has been declared) - although that could be considered nit-picking.
This is a valid example.
Functions in JavaScript are first order objects. They can be passed as an argument, returned from a function or even set to a variable. Therefore they are called 'lambda'.
So when you are directly using this function (without new keyword) you are directly dealing with the function as an object. When u are using new keyword, you are dealing with an object instance of the function.

Using instance variables/methods within Reactive Framework subscription in Javascript

I've got an object in JS in which I'm trying to test out the Reactive Framework In an event subscription I'd like to call an instance method of the enclosing class where the subscription is defined, like this;
function MyClass()
{
var DoSomething = function(a,b) { ... }
var InstanceVariable = 1;
this.uiEvent = uiDiv.jqueryUiWidget("widget")
.toObservable("change")
.Subscribe(
function (event)
{
// Want to call the instance method in the enclosing class
DoSomething(1,2);
});
this.uiEvent2 = uiDiv.jqueryUiWidget("widget")
.toObservable("change")
.Subscribe(
function (event)
{
// Want to use the instance variable within here
alert(InstanceVariable);
});
}
How can I do this (since the "this" scope is that of the subscription)? Do I have to pass the function/variable through when setting up the subscription in some way?
If I attempt to do this, I get an error in all browsers saying that the instance variables or methods don't exist: "this" within the scope of the function where I want to call the instance members refers to the Observer and so has functions of OnNext, OnCompleted etc.
Many Thanks,
Paul
Seems to me like your code should work. If you are having any problems I suggest you describe them. However, if you are asking how it works, then you should know about closures. From Wikipedia:
In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Closures are used to implement continuation passing style, and in this manner, hide state. Constructs such as objects and control structures can thus be implemented with closures.
This means that DoSomething and InstanceVariable are accessible from any method that is defined within the scope where they are defined. There will be a new "instance" of these variables each time the MyClass constructor is called.

Javascript scope chain

I am trying to optimize my program. I think I understand the basics of closure. I am confused about the scope chain though.
I know that in general you want a low scope (to access variables quickly).
Say I have the following object:
var my_object = (function(){
//private variables
var a_private = 0;
return{ //public
//public variables
a_public : 1,
//public methods
some_public : function(){
debugger;
alert(this.a_public);
alert(a_private);
};
};
})();
My understanding is that if I am in the some_public method I can access the private variables faster than the public ones. Is this correct?
My confusion comes with the scope level of this.
When the code is stopped at debugger, firebug shows the public variable inside the this keyword. The this word is not inside a scope level.
How fast is accessing this? Right now I am storing any this.properties as another local variable to avoid accessing it multiple times.
Thanks very much!
There are many good ways to optimize Javascript.
This is not one of them.
The cost of searching up the scope is minute.
In addition, you're misunderstanding the this keyword.
The this keyword is an implicit parameter to every function, which will either be the global window object, the instance that the function was called on, or the first parameter passed to call or apply.
The this object will refer to a normal Javascript object; its properties have no scope.
First, have you profiled your application and do you know that this code is a bottleneck?
There's no point optimizing this if your applications spends 99.9% of its time doing something else.

What kind of a pattern/object is this in Javascript?

I see this pattern a lot (which I actually use) but I want an explanation as to how it works.
var mystuff = function() {
var blah = function() {
};
return {
setup: function() {
blah();
};
};
}();
Then usage is very OOP like:
mystuff.setup();
What that's doing is returning a public interface to your object. It looks like you are using the public setup() function to access the private blah() function. This is one method of emulating public and private member functions in Javascript objects.
Since mystuff is defined with that trailing () at the bottom, it's executed immediately when the parser reaches mystuff.setup(), and actually returns an anonymous object (your public interface) with the setup() method.
Others have explained how it works. This is just somemore background info on the topic.
It's called the "Module pattern" (coined by Douglas Crockford I believe, but blogged about earlier).
It gives you three main benefits:
A namespace (the value to the left of "function")
A private "space" to put stuff in (vars, functions, etc) that don't need or should not pollute the global namespace (this is the stuff before the return statement)
A public "space" to put stuff that you want accessible to users of your namespace (this is the return statement)
all in a fairly readable form.
This is simply an example of nested functions in JavaScript. Although the method of calling them may seem "OOP-like" on the surface, this style very much belongs to the functional paradigm.
In essence, however, there's nothing too fancy going on. JavaScript is known as a language in which "everything is a function", which is close enough to the truth. All it means is that any function declared belongs strictly to its parent scope.
It's from a functional programming approach to object oriented programming. Local variables in the outer (anonymous) function (the constructor) are accessible to any function defined within the constructor, but not elsewhere, making the local variables private. Where it differs from the purely functional approach is that the constructor returns an object literal rather than another function. The local variables are accessible by inner functions due to what's termed a closure.
It's use is to create private fields & methods, in the form of local variables.
but I want an explanation as to how it works.
Let's desect it piece by piece.
function() { .... } is a syntax for anonymous function.
function() { .... }() is defining and calling the anonymous function on the same line.
The return value of the function in your sample is an object defined using JSON notation (Javscript Object Notation)
{ setup : .... } is an object with one attribute: it's called setup, and it happens to be a function, in your case.
so, mystuff got the return value, which is an object with a property (function) called setup, and mystuff.setup() invokes this setup function.
Now, the interesting part is probably how setup just calls the blah function, defined inside that enclosing anonymous function.
I believe the technical term here is closure (see the section forming closures) (Also see the wikipedia definition)
Essentially the function becomes like a module of its own, with variables bound to it.
It's explained in crescentfresh's answer
First of all, please avoid this syntax:
var mystuff=function(){...}();
It is bad coding practice since it isn't completely cross-browser as a few browsers will error here.
Get used to putting parentheses around the function like so:\
var mystuff=(function(){...})();
Nextly, regarding the pattern. This pattern is more commonly known as simply "encapsulation" in JavaScript. Closures is another possibly but more specifically it is purely encapsulation in this case.
Encapsulation simply means you are making some members private. What is private in this case? Well the blah variable is private in this case. Please get into the habit of proceeding private members with an underscore to indiciate they are private. It is good coding practice to distinguish public methods from private methods with an underscore.
<script type="text/javascript">
var obj=(function(){
//private members
var _p={};//toss all private members into a single object.
_p.list=[];
_p.init=function(){
_p.list=[];
};
//public members. use "this" to reference object followed by the method.
//however obj._p.list won't be accessible to the global scope
return {
reset:function()
{
_p.init();
}
,addName:function(str)
{
_p.list.push(''+str);//limit to strings
}
,getNames:function()
{
return _p.list.slice(0);//return a clone
}
,alertNames:function()
{
alert(this.getNames().join(","));
}
,getPrivateObj:function()
{
return _p;
}
};
})();
obj.alertNames();
obj.addName("Nandan");
obj.addName("Ram");
obj.alertNames();
obj.reset();
obj.alertNames();
obj.addName("Vinoth");
obj.addName("Kevin");
obj.alertNames();
alert(typeof obj._p);//undefined
var privateObj=obj.getPrivateObj();
alert(typeof privateObj);
alert(privateObj.list.join("|"));
</script>

Categories

Resources