1

Jumping to code first:

function myClass(arg1,arg2){
    this.arg1=arg1;
    this.arg2=arg2;
}

myClass.prototype.sayArg=function(){
    console.log("First Arg is "+ arg1);
}
  1. Why do i have to add 'prototype' to declare a function for the class? Even if it would get extend, should every child would not get this method by default? What is it actually , i am juggling 'class' and 'prototype' from starting.I read this link , couldnt understand yet :(

  2. If i define my class with that literary(or just a '=new Object()' ) method , how can i define a constructor later , so that i could use

    var anObject=new myClass(arg1,arg2);
    
  3. If you notice , i havent used 'this.arg' in 6th line , and it is an error, which brings me to my last doubt. I am already specifying 'myClass.' means it belongs to myClass , still, it isn't able to access its 'arg1' member? Why i have to use 'this.' to acess it while it is in same class? Is it knid of private member? But as the function belongs to same class , it should get access to it ( kind of in c++ ).

Thanks :)

6502
  • 112,025
  • 15
  • 165
  • 265
Abhinav Gauniyal
  • 7,034
  • 7
  • 50
  • 93
  • 1
    There really is no such thing as a "Class" in JavaScript. Inheritance in JavaScript is much different than inheritance in other common languages like Java and C++. – Pointy Mar 16 '14 at 17:57
  • 1
    You're asking the most fundamental questions of prototypal inheritance. What you should do is read some instructional material. There's no shortage of information on the topic. – cookie monster Mar 16 '14 at 17:58
  • @Pointy , classes arent there in javascript? So there are objects , but no classes? What are objects of then( I mean their blueprint)? – Abhinav Gauniyal Mar 16 '14 at 18:00
  • @cookiemonster , any links , pointers or directions that would help me :) – Abhinav Gauniyal Mar 16 '14 at 18:01
  • Well, I suppose I could link to StackOverflow. You'll find lots of Q & A here. Also plenty of resources are listed here under the JavaScript tag wiki. MDN is also a good resource. And then there's Google of course. – cookie monster Mar 16 '14 at 18:05
  • Objects are just key-value stores. I mean, they have some additional, mostly internal behavior, but essentially they are just kv stores. http://es5.github.io/#x8.6 – Felix Kling Mar 16 '14 at 18:09
  • @AbhinavGauniyal there are facilities that provide functionality that is similar to the functionality you get from class-based inheritance systems like C++, but they are different in some very basic ways. – Pointy Mar 16 '14 at 18:09
  • Maybe the following answer can help you understand what prototype is and how JavaScript determines what this is. http://stackoverflow.com/a/16063711/1641941 maybe check out mdn as well how JavaScript scope works. – HMR Mar 16 '14 at 23:58

2 Answers2

4

It is important to build a mental model of how Javascript objects are implemented: if you're coming from a C++ background then consider this possible model

All objects in javascript are of the same class, the class "Object"

Each object is defined with something like

class Object {
    std::map<std::string, Object *> attributes;
};

and this means for example that

  1. The set of attributes is not fixed, you can add attributes at runtime to a specific object instance

  2. Inheritance doesn't work like in C++

Each object has a special attribute named constructor

The constructor of an object is the function that was used to instantiate the object. For example if you write

function Person(first_name, last_name) {
    this.first_name = first_name;
    this.last_name = last_name;
}

then executing

var p = new Person("Andrea", "Griffini");
alert(p.constructor === Person);

Will display "true" in a message box.

The constructor is an object too

The constructor of the constructor is Function, and as you probably guess it's an object too, with itself as constructor.

A constructor has a special attribute named prototype

This special attribute is what allows inheritance among other things. The rules followed by Javascript are simple: when accessing a attribute attr of an object x

  1. if the instance x has itself the requested attribute then the value is returned
  2. otherwise x.constructor.prototype is looked up for attr instead of x

The second step is also recursive, meaning that if x.constructor.prototype doesn't have the attribute either then x.constructor.prototype.constructor.prototype is searched instead and so on.

When setting an attribute however Javascript simply sets it in the instance, not following the constructor.prototype chain.

This explains the apparently strange behavior...

function Person(first_name, last_name) {
    this.first_name = first_name;
    this.last_name = last_name;
}

Person.prototype.display = function() {
    return this.first_name + ", " + this.last_name;
}

var p = new Person("Andrea", "Griffini");
var q = new Person("John", "Smith");

q.display = function() {
    return "... not sure ...";
}

alert(p.display()); // Says "Andrea, Griffini"
alert(q.display()); // Says "... not sure ..."

this is a run-time concept in Javascript

this can be seen simply as a global variable that is automatically set by Javascript: more specifically when you write

obj.method(...);

the method attribute is looked up as usual, but before being called this is set to obj and restored to its current value once the method returns; in other words what happens is more or less:

// Not real code, just to show the concept
var old_this = this;
this = obj;
method(...);
this = old_this;

and it also means that the two fragments

// First case
var f = obj.method;
f();

// Second case
obj.method();

are not equivalent, because in the first case the code of the method will be executed with this being "the global object", while in the second case this value will be obj during the execution of the method code. The this magic only happens if you call the result of an attribute lookup... even just using [obj.method][0]() is not the same as obj.method() because this will be the array (that has been looked up for the attribute 0) during the execution of method code.

This is not the whole truth

This reply only wants to give you a rough description of how things more or less are working in Javascript and of course they're not the truth but I think just these few ideas should be able to take you far enough into Javascript programming.

For the whole truth you'd need to read quite a bit more.

6502
  • 112,025
  • 15
  • 165
  • 265
3

JavaScript has no classes, just objects...

"One of the key differences is that JavaScript does not have classes; instead, the class functionality is accomplished by object prototypes."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript#Objects

I recommend you read this... it's probably the best introduction to JavaScript I've seen. It's not a big read, won't take you long and should help answer all your questions.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
Jon Miles
  • 9,605
  • 11
  • 46
  • 66