JavaScript functions have two distinct roles:
1- They can function as a method, similar to how you've used it in your second block.
2- They can also act as a Class to create objects, as demonstrated in your first block.
The same function can serve different purposes. For example:
var display = new displayValue();
This code indicates that you want to instantiate an object based on your Class (the function). By using the new
keyword, display
becomes a JavaScript object and its properties can be accessed like this: display.a
or display.b
. However, when used simply as a method like this:
displayValue('1','one');
In this case, the function is just being called. The important point here is that this
within this function will refer to the function's containing object, which is typically the top-level class or the window
object.
In your function:
function displayValue(a,b){
this.a = a;
this.b = b;
$('p').text(a + " " + b);
}
When you use this.a = a;
, it generally signifies that you intend to utilize it as a Class or as a method within the top-level class, like so:
function Display(){
this.displayValue=function displayValue(a,b){
this.a = a;
this.b = b;
$('p').text(a + " " + b);
}
}
or
function Display(){
//constructor
}
Display.prototype.displayValue = function displayValue(a,b){
this.a = a;
this.b = b;
$('p').text(a + " " + b);
};
In this scenario, if you attempt var obj = new Display();
, the this
keyword within the displayValue
function will point to the current instance of Display
, which is obj
.