Javascript Static Method vs Instance Method - javascript

So I am new to javascript (or any programming language) and as I progress I hear new keywords.
I was going through this question on Stackoverflow: How to access a method from a class from another class?
Where the reply or answerer wrote something like this..
if it's a static method (doesn't use any instance data), then declare it as a static method and you can directly call it.
If it's an instance method, then you would typically create an object of type one and then call the method on that object (usually in the constructor).
Can someone explain the difference Between Static and Instance Method with examples? How do we call static and instance method in javascript?

This answer is not for Javascript, but OOP in general.
Imagine, you have a class Person. An instance of that class could be daniel.
Instance method
You could call a method on daniel, e.g: daniel.talk(), so daniel starts talking...
Static method
You could call an static method on class Person, instead of on a concrete instance, for example: Person.getPeopleFromNewYork(). Note that getPeopleFromNewYork is not related to any instance of Person but to the class itself.
(Tipically, a method like getPeopleFromNewYork() would belong to some kind of repository, but it's just for the example.)
Another illustrative examples for understand static methods are Math.sum(2, 5) or Random.randomInt()

Javascript has two type of property and method. Static and instance both type of property and method can you use.
First of all you need to know how object can defined in javascript .. Two major way is using {} or using constructor. in {} every property and method is static and you can not create an instance of that , such as :
<script>
var person = {name:"Chayon Shaah",age:"30",say:function(){return "Hello "+this.name}}
alert(person.say()); // will allert "Hello Chayon Shaah"
</script>
just see the code , here you need to call any property or method by object reference and can't creat any instance of this person object using new keyword
and now see the constructor , how it can create an instance :
<script>
function Person(){
this.name="Chayon Shaah",
this.age = 30,
this.say = function(){
return "Hello "+this.name;
}
}
var obj = new Person();
alert(obj.say()); // will alert "Hello Chayon Shaah"
</script>
Here all of Person object properties and method can be accessed by the "obj" whice is an instance of Person object.
Person object directly can not access them , only its any instance can access them . On the other hand you can use static property or method for Person object whic can only acess by its own not by its any instance.
let's add some more instance property and static property in Person object ...
<script>
function Person(){
this.name="Chayon Shaah",
this.age = 30,
this.say = function(){
return "Hello "+this.name;
}
}
var obj = new Person();
alert(obj.say());
Person.prototype.city = "Mymensingh"; // only can be used by all instances of Person object (non static property).
alert(obj.city); // Will alert "Mymensing" (Calling via instance of Person)
Person.location = "Bangladesh"; //This is a static property which can not be accessed by any instance of Person object, Only accessed by Person Object.
`alert(Person.location); // Will alert "Bangladesh" (Calling directly via` Person object)
</script>
use "prototype" keyword for making any instance method or property with the main object name, If you want to make static property and method then just use the name without use "prototype" keyword like the example .
I Think it will help you ...

For Javascript specific answer please visit this link ( I found it by googling ) It seems good.
But regardless of which object oriented programming language you've chosen; generally you'd use a static method for functionalities which don't need to know other field/property status of the class. For example, converting one unit of length to another doesn't need to know what are other properties of the object. On the other hand, let's assume that we have a class Customer with properties first name and last name. Now if you needed to derive full name by concatenating first and last name you'd could create a method on class GetFullName() which doesn't take parameters and does the job for you. So on object of type Customer you could use object.GetFullName() without any parameters to get the full name. Of course, you could write a static method for the same purpose but then you'd have to pass parameters to the method. For a method which depends on a large number of parameters, it would be cumbersome.

Related

Should prototype only be used for public methods in a class?

I have a js class that has no public methods. I'm using var's inside a constructor to create these methods and call them with methodName(). Should I use class.prototype.methodName instead and call them within the class with this.methodName()? What's the advantage of either approach? I know prototype methods get copied over to new instances, and thus is faster. But should they be used only for the API of the class?
JavaScript doesn't have private vairables, thus using a pattern that simulates them causes some overhead (more cpu and memory is needed to run your code). Code with privates can be harder to maintain.
The pattern that simulates private members can be split up in 2 different types:
Instance specific members
Prototype Members
Instance specific could be something like a person's religion and prototype member could be the doSomethingDangerous function. Before religion returns a value you may want to check if the requesting object has access to this private information. The function doSomethingDangerous should not be called directly because you can't be sure that when called from outside Person the right precautions have been taken before doing it.
Methods that can access "private" members are privileged methods. If they need to access instance specific members they need to be in the constructor body (that is where instance specific members are declared). If they need to access prototype specific members they need to be in the same body as where the "private" is declared.
Here is an example:
//constructor for Person
var Person = function(){//<=start body of constructor function
//to properly use prototype and not cause your code to consume
// more resources to simulate something that isn't supported
// in JavaScript "private" variable names usually start with _
// so other programmers know not to set, get or call this directly
this._normalPrivate;
var religion = undefined;//<=instance specific private
this.religion = function(){//<=privileged function
console.log(religion);//<=can access private instance here
}
};
Person.prototype=(function(){//<=start body of function returning object for prototype
//All person instances share this, it's not instance specific
var doSomethingDangerous=function(){//<=private prototype
// doing something dangerous, don't want this to be called directly
};
return {
doSomething:function(){//<=priviliged method, can access private prototype
//we cannot access religion because it's defined in a different
// function body
//make sure we can do something dangerous
doSomethingDangerous();
}
};
}());
Person.prototype.constructor=Person;
Person.prototype.anotherMethod=function(){
//not a privileged method, cannot access doSomethingDangerous or religion
};
var ben = new Person();
I never use this pattern though because private is only used to indicate to other programmers not to directly access these members. As in the following example you don't want a programmer (including yourself in the future) to do something like:
ben._doSomethingDangerous();
To indicate to other programmers (and future self) that doSomethingDangerous is private you can add an underscore in front of it:
Person.prototype._doSomethingDangerous=function(){...
More on prototype, inheritance, mix ins here https://stackoverflow.com/a/16063711/1641941

If Javascript's native OOP is classless, what about the constructor? Doesn't that imply a class?

I think Javascript native OOP system is said to be classless, and is object-based, not class-based. But every example I see always start with a constructor similar to
function Person(name) {
this.name = name;
}
Just by using a constructor this way, doesn't this already imply a class is being used? (a class called Person)
Details:
If we can use
a.__proto__ = b;
on any Javascript platform, then I think it is classless. But we can't do that. If we want that behavior, we need to use
function F() { }
F.prototype = b;
a = new F();
and so, a constructor has to be used. So if constructor is such a cornerstone in Javascript, that means it is intended to be constructor of Person, Widget, etc, and these are classes.
The OOP in Javascript is slightly different from, for instance, the Java OOP.
The Javascript constructors do not refer to a class definition (so it is classless). Rather the constructor refers to a prototype. The base of the OOP in Javascript is the Object object (not the Object class), from where all the others objects are derived.
Prototyping grants you inheritance, and the possibility to extend an existing object with properties and methods.
I suggest you this article.
In your example:
function Person(name) {
this.name = name;
}
Mike = new Person('Mike');
the Person() function lets you create a new object prototyped on the Object object with a new property called name. Well, such a kind of function in Javascript oop is called a constructor.
Classless may be an inaccurate way to describe JavaScript's approach on OOP.
JavaScript does lack class definitions.
It also lacks a class-to-object correspondence.
You can't check if an object instantiated with a constructor such as Person is of class Person.
You can check if it contains the expected object members and conclude that it is of the expected class.
But if the object members have been changed along the way you're not going to get the desired/expected result.
TL;DR
JavaScript exposes constructors (appropriately named prototypes) as a manner in which you can define a template for constructing plain objects.
The important thing is that the end result of a prototype call is a plain object with some predefined members and not an object of a certain class .
It's good to think of javascript as a classless environment. If you think javascript classes you should be able to assume there's certain useful things you can do when there are classes and they're strictly enforced. However those certain useful things you cannot assume. The presence of something that looks like a constructor does not indicate you're creating a class.
For example, let's say you var dude = Person('Ashton Kutcher'). Now, when you dude instanceOf person, you get true. You assume you have the properties and methods of a person. What if some code comes along and says dude.personMethod = undefined. Now, while dude instanceOf person will still be true, the personMethod is no longer available.
You can think of javascript as having classes but it's a leaky abstraction. It's better to think of javascript as having a prototypal inheritance system when it comes to determining what something is and what you can expect of it.
More information here: http://javascript.crockford.com/prototypal.html
Create a class using the Object Constructor and prototyping can help us
in creating many instances of the class without redefining the object each time wee need it.
so in the above example
function Person(name)
{
this.name = name;
}
you can create two persons with different names.
example :
var personA = new Person();
personA.name = "james";
var personB = new Person();
personB.name = "Tom";
alert(personA.name + personB.name);
i suggest you reading this link will be helpful
http://www.javascriptkit.com/javatutors/oopjs2.shtml

what is the meaning of word this near the property in JavaScript

Hello I'm a newcomerin JavaScript language.
I started to see some examples of JavaScript code.
and i cant understand the following code segment:
function Employee(name,salary)
{
this.name=name;
this.salary=salary;
this.paycheck=function()
{
var monthly=this.salary/12;
document.write(this.name+ ": " +monthly);
};
}
var emp= new Employee("Fred",10000);
emp.paycheck();
My question: what is the meaning of word this near the property inside class (i.e. ,this.name=name; this.salary=salary; )?
Thank you in advance!
The use of this could be explained as meaning "properties that apply to this instance". Since Employee is a constructor function (you create instances of it using the new operator), every instance has its own values for those properties:
var me = new Employee("James", 2000000); //Instance of Employee
console.log(me.name); //Prints James
var you = new Employee("Michael", 2000000); //Another instance
console.log(you.name); //Prints Michael
Note that this also means every instance of Employee has its own copy of the paycheck method. This is not particularly efficient, as a separate copy of the function has to be stored in memory for every instance of the object. You could instead declare the method on the prototype of the Employee object, which would mean the method would be shared between all instances.
In JavaScript this always refers to the “owner” of the function we're
executing, or rather, to the object that a function is a method of.
When we define our faithful function doSomething() in a page, its
owner is the page, or rather, the window object (or global object) of
JavaScript. An onclick property, though, is owned by the HTML element
it belongs to.
For further reading see these links:
http://www.quirksmode.org/js/this.html
http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/
http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
this is a reference to the calling context of the function.
Its value will be different based on how a function is invoked.
In your case, because Employee is invoked using new, it's a reference to the new object being constructed.
So when you do...
this.name=name;
...what's happening is that the new object you're creating is being assigned a property name, and its value is being set to whatever was passed to the name parameter of the function.
Here's one way to demonstrate it.
Simplify your function like this...
var foo;
function Employee() {
foo = this;
}
So now all Employee does is set its this value to the outer variable foo.
Now lets create a new object
var bar = new Employee();
So bar has been assigned whatever Employee returned. If this is the new object constructed, and we assigned it to foo, then foo and bar should have the same object.
foo === bar; // true
In this case the Employee function is used a constructor. When the new Employee() syntax is used (as opposed to simply calling Employee()), this refers to an object that you are about to create, which is later assigned to emp variable.
it's a definition of properties inside the class.
You can read short information about it here http://www.phpied.com/3-ways-to-define-a-javascript-class/
this always refers to the “owner” of the function we're executing

What does `this` refer to?

I have a JavaScript class:
function Person(n){
// ...
}
Outside of the class, I have the following code:
Person.prototype.shower = function(){ this.dirtFactor=2 }
What does this in the above code refer to? Does it refer to prototype, or to the Person class?
The meaning of this depends on how you call the function, not how you define it.
Assuming you do something like:
var bob = new Person('whatever n is');
bob.shower();
Then this will be bob (which will be an instance of Person).
Okay, basics first: when you write function Person(o) { ... }, you are not declaring a class -- JavaScript does not class based, but object based. This statement simply declares a function (which incidentally, are objects as well).
Next, when you create an object like this:
var mellon = new Person('Mellon');
you are creating an object, whose constructor (of sorts) is Person.
Now, read this carefully: since mellon's constructor is Person, all methods in Person's prototype will be available in the object.
So if you write:
Person.prototype.shower = function(){ this.dirtFactor=2 }
then the method mellon.shower() will be available.
I recommend going through Mozilla's intro to OOP in Javascript for some details on this topic.
So to answer your question: this refers to the object with which the method shower was invoked. In the above case, it would be mellon.
It refers to the instance of the person
So when you do a
var Mike = new Person();
then this is Mike
Example
<input type="text" id="field" value="Bla" />
<script>
document.getElementById('field').onfocus=function() {
alert(this.value)
}
</script>
will alert the value of the field the function is assigned to
It reffers to a instance of Person class
var instance = new Person( ... );
instance.shower(); // Here will be this.dirtFactor assigned to instance.dirtFactor
This refers to the object upon which shower is called. Specifically, you will eventually end up doing
p = new Person(n);
This will execute the Person function and create a new, empty object which will be accessible as this in the constructor. That object will then be given a link to Person.prototype and any attribute references that fail on p will look on Person.prototype to see if it's found there.
If it's called on p, using p.shower(), then this will return to p. The point is though that there aren't instances and classes in javascript. Person.prototype is one object and all objects that are constructed by Person will share a reference to it.
Removing prototypes all together, you can just do
person = {'shower': function () {
this.dirtFactor = 2; }
}
person.shower();
console.log(person.dirtFactor);
and you will see that this still refers to the object upon which you called the method.

Understanding prototypal inheritance in JavaScript

I am new to JavaScript OOP. Can you please explain the difference between the following blocks of code? I tested and both blocks work. What's the best practice and why?
First block:
function Car(name){
this.Name = name;
}
Car.prototype.Drive = function(){
console.log("My name is " + this.Name + " and I'm driving.");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar;
function SuperCar(name){
Car.call(this, name);
}
SuperCar.prototype.Fly = function(){
console.log("My name is " + this.Name + " and I'm flying!");
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
Second block:
function Car(name){
this.Name = name;
this.Drive = function(){
console.log("My name is " + this.Name + " and I'm driving.");
}
}
SuperCar.prototype = new Car();
function SuperCar(name){
Car.call(this, name);
this.Fly = function(){
console.log("My name is " + this.Name + " and I'm flying!");
}
}
var myCar = new Car("Car");
myCar.Drive();
var mySuperCar = new SuperCar("SuperCar");
mySuperCar.Drive();
mySuperCar.Fly();
Why did the author add the Drive and Fly methods using prototype, and did not declare them as a this.Drive method inside the Car class and as this.Fly in the SuperCar class?
Why does SuperCar.prototype.constructor need to be set back to SuperCar? Is the constructor property overridden when prototype is set? I commented out this line and nothing changed.
Why call Car.call(this, name); in the SuperCar constructor? Won't properties and methods of Car be 'inherited' when I do
var myCar = new Car("Car");
To add to Norbert Hartl's answer, SuperCar.prototype.constructor isn't needed, but some people use it as a convenient way of getting the constructing function of an object (SuperCar objects in this case).
Just from the first example, Car.call(this, name) is in the SuperCar constructor function because when you do this:
var mySuperCar = new SuperCar("SuperCar");
This is what JavaScript does:
A fresh, blank object is instantiated.
The fresh object's internal prototype is set to Car.
The SuperCar constructor function runs.
The finished object is returned and set in mySuperCar.
Notice how JavaScript didn't call Car for you. Prototypes being as they are, any property or method that you don't set yourself for SuperCar will be looked up in Car. Sometimes this is good, e.g. SuperCar doesn't have a Drive method, but it can share Car's one, so all SuperCars will use the same Drive method. Other times you don't want sharing, like each SuperCar having its own Name. So how does one go about setting each SuperCar's name to its own thing? You could set this. Name inside the SuperCar constructor function:
function SuperCar(name){
this.Name = name;
}
This works, but wait a second. Didn't we do exactly the same thing in the Car constructor? Don't want to repeat ourselves. Since Car sets the name already, let's just call it.
function SuperCar(name){
this = Car(name);
}
Whoops, you never want to change the special this object reference. Remember the 4 steps? Hang onto that object that JavaScript gave you, because it's the only way to keep the precious internal prototype link between your SuperCar object and Car. So how do we set Name, without repeating ourselves and without throwing away our fresh SuperCar object JavaScript spent so much special effort to prepare for us?
Two things. One: the meaning of this is flexible. Two: Car is a function. It's possible to call Car, not with a pristine, fresh instantiated object, but instead with, say, a SuperCar object. That gives us the final solution, which is part of the first example in your question:
function SuperCar(name){
Car.call(this, name);
}
As a function, Car is allowed to be invoked with the function's call method, which changes the meaning of this within Car to the SuperCar instance we're building up. Presto! Now each SuperCar gets its own Name property.
To wrap up, Car.call(this, name) in the SuperCar constructor gives each new SuperCar object its own unique Name property, but without duplicating the code that's already in Car.
Prototypes aren't scary once you understand them, but they're not much like the classic class/inheritence OOP model at all. I wrote an article about the prototypes concept in JavaScript. It's written for a game engine that uses JavaScript, but it's the same JavaScript engine used by Firefox, so it should all be relevant.
The two blocks differ in a way that in the first example Drive() will only exist once while at the second approach Drive() will exist per instance (Every time you do new Car() the function drive() will be created again). Or different said the first uses the prototype to store the function and the second the constructor. The lookup for functions is constructor and then prototype. So for your lookup of Drive() it finds it regardless if it is in the constructor or in the prototype. Using the prototype is more efficient because usually you need a function only once per type.
The new call in javascript automatically sets the constructor in the prototype. If you are overwriting the prototype so you have to set the constructor manually.
Inheritance in javascript has nothing like super. So if you have a subclass the only chance to call the super constructor is by its name.
Norbert, you should note that your first example is pretty much what Douglas Crockford calls pseudoclassical inheritance. Something things to note about this:
You will call the Car constructor twice, once from the SuperCar.prototype = new Car() line and the other from the "constructor stealing" line Car.call(this...you can create a helper method to inherit prototypes instead and your Car constructor will only have to run once making the setup more efficient.
The SuperCar.prototype.constructor = SuperCar line will allow you to use instanceof to identify the constructor. Some folks want this others just avoid using instanceof
Reference vars like: var arr = ['one','two'] when defined on the super (eg Car) will get shared by ALL instances. This means inst1.arr.push['three'], inst2.arr.push['four'], etc., will show up for all instances! Essentially, static behavior that you probably don't want.
You second block defines the fly method in the constructor. This means for every time that it's called, a "method object" will be created. Better to use a prototype for methods! You CAN however keep it in the constructor if you'd like - you just need to guard so you only actually initialize the prototype literal once (pseudo): if (SuperCar.prototype.myMethod != 'function')...then define your prototype literal.
'Why call Car.call(this, name)....': I don't have time to look carefully at your code so I may be wrong but this is usually so that each instance can keep it's own state to fix the 'staticy' behavior issue of prototype chaining that I described above.
Lastly, I'd like to mention that I have several examples of TDD JavaScript Inheritance code that works here: TDD JavaScript Inheritance Code and Essay I'd love to get your feedback as I'm hoping to improve it and keep it open source. The goal is to help classical programmers get up to speed with JavaScript quickly and also supplement the study both Crockford and Zakas books.
I am not 100% sure, but I believe the difference is that the second example simply duplicates the contents of the Car class into the SuperCar object, while the first links the SuperCar prototype to the Car class, so that run-time changes to the Car class affect the SuperCar class as well.
function abc() {
}
Prototype methods and property created for function abc
abc.prototype.testProperty = 'Hi, I am prototype property';
abc.prototype.testMethod = function() {
alert('Hi i am prototype method')
}
Creating new instances for function abc
var objx = new abc();
console.log(objx.testProperty); // will display Hi, I am prototype property
objx.testMethod();// alert Hi i am prototype method
var objy = new abc();
console.log(objy.testProperty); //will display Hi, I am prototype property
objy.testProperty = Hi, I am over-ridden prototype property
console.log(objy.testProperty); //will display Hi, I am over-ridden prototype property
http://astutejs.blogspot.in/2015/10/javascript-prototype-is-easy.html
There are several questions here:
Can you please explain the difference between the following blocks of code. I tested and both blocks work.
The first only creates one Drive function, the second creates two of them: one on myCar and another one on mySuperCar.
Here is code that would give different results when either the first or second block was executed:
myCar.Fly === mySuperCar.Fly // true only in the first case
Object.keys(myCar).includes("Fly") // true only in the second case
Object.keys(Car.prototype).length === 0 // true only in the second case
What's the best practice and why?
Why did the author add Drive and Fly methods using prototype, but doesn't declare them as this.Drive method inside Car class and this.Fly in SuperCar class?
It is better practice to define methods on the prototype, because:
each method is only defined once
each method is also available to instances that were created without executing the constructor (which is the case when calling Object.create(Car.prototype));
you can inspect at which level in an instance's prototype chain a certain method got defined.
Why does SuperCar.prototype.constructor need to be set back to SuperCar? Is constructor property overridden when prototype is set? I commented out this line and nothing changed.
The constructor property is not overridden when prototype is set. But the constructor of new Car() is Car, so if you set new Car() to SuperCar.prototype, then obviously SuperCar.prototype.constructor is Car.
As long as you don't reassign to prototype, there is an invariance: Constructor.prototype.constructor === Constructor. For example, this is true for Car: Car.prototype.constructor === Car, but it is equally true for Array, Object, String, ...etc.
But if you reassign a different object to prototype, that invariance is broken. Usually this is not a problem (as you have noticed), but it is better to reinstate it, because it answers the question "Which constructor uses this prototype object when creating new instances?" Some code may do such inspection and depend on it. See "Why is it necessary to set the prototype constructor?" for such cases.
Why call Car.call(this, name); in SuperCar constructor? Won't properties and methods of Car be 'inherited' when I do
var myCar = new Car("Car");
If you don't do Car.call(this, name); then your SuperCar instance will not have a name property. You could of course decide to just do this.name = name; instead, which just copies the code that is in the Car constructor, but in more complex situations it would be bad practice to have such code duplication.
It would not be helpful to call new Car(name) within the SuperCar constructor, as that will create another object, while you really need to extend the this object. By not using new (using call instead) you actually tell the Car function to not run as a constructor (i.e. to not create a new object), but to use the object you pass to it instead.
Times have changed
In modern versions of JavaScript you can use super(name) instead of Car.call(this, name):
function SuperCar(name) {
super(name);
}
Today, you would also use the class syntax and write the first code block from the question as follows:
class Car {
constructor(name) {
this.name = name;
}
drive() {
console.log(`My name is ${this.name} and I'm driving.`);
}
}
class SuperCar extends Car {
constructor(name) {
super(name);
}
fly() {
console.log(`My name is ${this.name} and I'm flying!`);
}
}
const myCar = new Car("Car");
myCar.drive();
const mySuperCar = new SuperCar("SuperCar");
mySuperCar.drive();
mySuperCar.fly();
Note how you don't even have to mention the prototype property to achieve the goal. The class ... extends syntax also takes care of setting the prototype.constructor property as the first block in your question did.

Categories

Resources