Rectangle 27 4

function sendMessage(msg) {
        waitForSocketConnection(nvWS, function() {
            ws.send(msg);
        });
    };


function waitForSocketConnection(socket, callback){
        setTimeout(
            function(){
                if (socket.readyState === 1) {
                    if(callback !== undefined){
                        callback();
                    }
                    return;
                } else {
                    waitForSocketConnection(socket,callback);
                }
            }, 5);
    };

javascript - Tornado WebSockets - InvalidStateError "Still in CONNECTI...

javascript python ssl websocket tornado
Rectangle 27 95

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.

+1 for mentioning the Chrome Dev Tools and window.location, Thanks!

php - how to get the base url in javascript - Stack Overflow

javascript php html css codeigniter
Rectangle 27 213

Falsey values in JavaScript

  • 0 and -0
""
''
null
undefined
  • document.all (in HTML browsers only) - this is a weird one, it's a falsey object, with typeof as undefined. It was a Microsoft-proprietory function in IE before IE11, and was added to the HTML spec as a "willful violation of the JavaScript specification" so that sites written for IE wouldn't break on trying to access, for example, document.all.something; it's falsy because if (document.all) used to be a popular way to detect IE, before conditional comments. See Why is document.all falsy? for details

"Falsey" simply means that JavaScript's internal ToBoolean function returns false.

ToBoolean
!value
value ? ... : ...;
if(value){...}else{...}

It's worth talking about falsy values' loose comparisons with ==, which uses ToNumber() and can cause some confusion due to the underlying differences. They effectively form three groups:

false, 0, -0, "", ''
false == ""
'' == 0
4/2 - 2 == 'some string'.slice(11);
null, undefined
==
null == undefined
undefined != false
  • It's also worth mentioning that while typeof null returns 'object', null is not an object, this is a longstanding bug/quirk that was not fixed in order to maintain compatibility. It's not a true object, and objects are truthy (except for that "wilful violation" document.all when Javascript is implemented in HTML)
NaN
NaN != NaN
NaN !== NaN
NaN != false
NaN != null
===
false

"Truthy" simply means that JavaScript's internal ToBoolean function returns true. A quirk of Javascript to be aware of: it is possible for a value to be truthy (ToBoolean returns true), but also == false.

You might think if( value && value==false ){ alert("huh?"); } is a logical impossibility that couldn't happen, but it will, for:

  • "0" and '0' - they're non-empty strings, which are truthy, but Javascript's == matches numbers with equivalent strings (e.g. 42 == "42"). Since 0 == false, if "0"==0, "0"==false.
  • new Number(0) and new Boolean(false) - they're objects, which are truthy, but == sees their values, which == false.
  • 0 .toExponential(); - an object with a numerical value equivalent to 0
  • Any similar constructions that give you a false-equaling value wrapped in a type that is truthy
[[]]
[0]

These are just a few values that some people might expect to be falsey, but are actually truthy.

  • -1 and all non-zero negative numbers
' '
" "
"false"
'null'

Anything from typeof, which always returns a non-empty string, for example:

'object'
'undefined'

Any object (keep in mind that null isn't really an object), including:

{}
[]
  • function(){} (any variable defined as a function, including empty functions)
  • Anything created with new (including otherwise-falsey values created with new, see above)

true, 1, "1" and [1] return true when compared to each other with ==.

FYI, what !, if and ?..: have in common is that they call the internal ToBoolean function on the value. How those values behave in the context of !, if, etc. is already implied by their name: They are "falsy" values. I'm a bit afraid that others will read the answer and think "Oh so in this context (!, if, ?...:), the value is false, but with !!, it's true", but don't understand the underlying concept. Two other points: 1) v ? true : false is just a verbose way of !!v. 2) typeof always returns a non-empty string, which is truthy.

typeof null
typeof undefined

I see, but this has nothing to do with the original question ;) Adding too much somewhat related but not relevant information could be rather confusing for readers.

document.all

Regarding loose comparison: because Booleans are converted to numbers, x == false will call ToNumber(x) which is just very different from ToBoolean(x). Might be worth explaining. Also I just noticed that I already commented on this answer ages ago :D

All falsey values in JavaScript - Stack Overflow

javascript
Rectangle 27 20

You could send messages via a proxy function that waits for the readyState to be 1.

this.send = function (message, callback) {
    this.waitForConnection(function () {
        ws.send(message);
        if (typeof callback !== 'undefined') {
          callback();
        }
    }, 1000);
};

this.waitForConnection = function (callback, interval) {
    if (ws.readyState === 1) {
        callback();
    } else {
        var that = this;
        // optional: implement backoff for interval here
        setTimeout(function () {
            that.waitForConnection(callback, interval);
        }, interval);
    }
};

Then use this.send in place of ws.send, and put the code that should be run afterwards in a callback:

this.ident = function () {
    var session = "Test";
    this.send(session, function () {
        window.identified = true;
        theText.value = "Hello!";
        say.click();
        theText.disabled = false;
    });
};
interval
that.waitForConnection(callback, interval)
setTimeout

javascript - Uncaught InvalidStateError: Failed to execute 'send' on '...

javascript exception-handling websocket
Rectangle 27 279

Number Formatting in JavaScript

I got to this question page hoping to find how to format numbers in JavaScript, without introducing yet another library. Here's what I've found:

The equivalent of sprintf("%.2f", num) in JavaScript seems to be num.toFixed(2), which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math.round below).

12.345.toFixed(2); // returns "12.35" (rounding!)
12.3.toFixed(2); // returns "12.30" (zero padding)
sprintf("%.2e", num)
num.toExponential(2)
33333 .toExponential(2); // "3.33e+4"
//   ^ Note the space, which keeps the . from being a decimal point.
//     Leaving out the space is a syntax error :-(

To print numbers in base B, try num.toString(B). JavaScript supports automatic conversion to and from bases 2 through 36 (in addition, some browsers have limited support for base64 encoding).

3735928559 .toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559

Wouldn't it just be better to enclose the number literal in parenthesis, instead of leaving a weird white space there?

Just a side note if you're using an older browser, or supporting older browsers, some browsers implemented toFixed incorrectly, using Math.round in place of toFixed is a better solution.

..
33333..toExponential(2);

JavaScript equivalent to printf/string.format - Stack Overflow

javascript printf string.format
Rectangle 27 278

Number Formatting in JavaScript

I got to this question page hoping to find how to format numbers in JavaScript, without introducing yet another library. Here's what I've found:

The equivalent of sprintf("%.2f", num) in JavaScript seems to be num.toFixed(2), which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math.round below).

12.345.toFixed(2); // returns "12.35" (rounding!)
12.3.toFixed(2); // returns "12.30" (zero padding)
sprintf("%.2e", num)
num.toExponential(2)
33333 .toExponential(2); // "3.33e+4"
//   ^ Note the space, which keeps the . from being a decimal point.
//     Leaving out the space is a syntax error :-(

To print numbers in base B, try num.toString(B). JavaScript supports automatic conversion to and from bases 2 through 36 (in addition, some browsers have limited support for base64 encoding).

3735928559 .toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559

Wouldn't it just be better to enclose the number literal in parenthesis, instead of leaving a weird white space there?

Just a side note if you're using an older browser, or supporting older browsers, some browsers implemented toFixed incorrectly, using Math.round in place of toFixed is a better solution.

..
33333..toExponential(2);

JavaScript equivalent to printf/string.format - Stack Overflow

javascript printf string.format
Rectangle 27 278

Number Formatting in JavaScript

I got to this question page hoping to find how to format numbers in JavaScript, without introducing yet another library. Here's what I've found:

The equivalent of sprintf("%.2f", num) in JavaScript seems to be num.toFixed(2), which formats num to 2 decimal places, with rounding (but see @ars265's comment about Math.round below).

12.345.toFixed(2); // returns "12.35" (rounding!)
12.3.toFixed(2); // returns "12.30" (zero padding)
sprintf("%.2e", num)
num.toExponential(2)
33333 .toExponential(2); // "3.33e+4"
//   ^ Note the space, which keeps the . from being a decimal point.
//     Leaving out the space is a syntax error :-(

To print numbers in base B, try num.toString(B). JavaScript supports automatic conversion to and from bases 2 through 36 (in addition, some browsers have limited support for base64 encoding).

3735928559 .toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559

Wouldn't it just be better to enclose the number literal in parenthesis, instead of leaving a weird white space there?

Just a side note if you're using an older browser, or supporting older browsers, some browsers implemented toFixed incorrectly, using Math.round in place of toFixed is a better solution.

..
33333..toExponential(2);

JavaScript equivalent to printf/string.format - Stack Overflow

javascript printf string.format
Rectangle 27 28

Classical Inheritance in JavaScript

I don't want to be discouraging since you seem to be a fairly new member of StackOverflow, however I'm going to have to be a little in your face and say that it's a really bad idea to try to implement classical inheritance in JavaScript.

Note: When I say that it's a bad idea to implement classical inheritance in JavaScript I mean that trying to simulate actual classes, interfaces, access modifiers, etc. in JavaScript is a bad idea. Nevertheless, classical inheritance as a design pattern in JavaScript is useful as it's just syntactic sugar for prototypal inheritance (e.g. maximally minimal classes). I use this design pattern in my code all the time (a la augment).

JavaScript is a prototypal object-oriented programming language. Not a classical object-oriented programming language. Sure, you can implement classical inheritance on top of JavaScript but before you do keep the following things in mind:

  • You're going against the spirit of the language, which means that you'll be faced with problems. Lots of problems - performance, readability, maintainability, etc.
  • You don't need classes. Thomas, I know that you truly believe that you need classes but trust me on this. You don't.

Most programmers start with trying to implement classical inheritance in JavaScript. Even JavaScript Gurus like Douglas Crockford tried to implement classical inheritance in JavaScript. I too tried to implement classical inheritance in JavaScript.

First I created a library called Clockwork and then augment. However I wouldn't recommend you to use either of these libraries because they go against the spirit of JavaScript. The truth is that I was still an amateur JavaScript programmer when I wrote these classical inheritance libraries.

The only reason I mention this is because everyone is an amateur at some point of time, and although I would prefer that you didn't use classical inheritance patterns in JavaScript, I can't expect you to understand why prototypal inheritance matters just yet.

You can't learn how to cycle without falling down a few times. I believe you're still in the learning phase with respect to prototypal inheritance. Your need for classical inheritance is like the training wheels on cycles.

Nevertheless, training wheels are important. If you want there are some classical inheritance libraries out there which should make you more comfortable writing code in JavaScript. One such library is jTypes. Just remember to take off the training wheels when you are confident of your skills as a JavaScript programmer.

I'm writing this section as a milestone for you so that you can come back later and know what to do next when you are ready to learn about true prototypal inheritance.

First of all the following line is wrong:

The javascript prototype-based object-oriented programming style is interesting, but there are a lot of situations where you need the ability to create objects from a class.

  • You will never need to create objects from a class in JavaScript.
  • There is no way to create a class in JavaScript.

Yes it's possible to simulate classical inheritance in JavaScript. However you're still inheriting properties from objects and not classes. For example, ECMAScript Harmony classes are just syntactic sugar for the classical pattern of prototypal inheritance.

In the same context the example you gave is also wrong:

For instance in a vector drawing application, the workspace will usually be empty at the beginning of the drawing : I cannot create a new "line" from an existing one. More generally, every situation where objects are being dynamically created require the use of classes.

Yes you can create a new line from an existing one even though the workspace is empty in the beginning. What you need to understand is that the line is not actually drawn though.

var line = {
    x1: 0,
    y1: 0,
    x2: 0,
    y2: 0,
    draw: function () {
        // drawing logic
    },
    create: function (x1, y1, x2, y2) {
        var line = Object.create(this);
        line.x1 = x1;
        line.y1 = y1;
        line.x2 = x2;
        line.y2 = y2;
        return line;
    }
};

Now you can draw your the above line by simply calling line.draw or else you could create a new line from it:

var line2 = line.create(0, 0, 0, 100);
var line3 = line.create(0, 100, 100, 100);
var line4 = line.create(100, 100, 100, 0);
var line5 = line.create(100, 0, 0, 0);

line2.draw();
line3.draw();
line4.draw();
line5.draw();

The lines line2, line3, line4 and line5 form a 100x100 square when drawn.

So you see you really don't need classes in JavaScript. Objects are enough. Encapsulation can be easily achieved using functions.

That being said you can't have public functions of each instance access the private state of the object without each instance having its own set of public functions.

This is not a problem however because:

  • You don't really need private state. You may think that you do, but you really don't.
  • If you really want to make a variable private then as ThiefMaster mentioned just prefix the variable name with an underscore and tell your users not to mess with it.

No ways to have class-based objects in javascript? - Stack Overflow

javascript class oop private
Rectangle 27 151

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 147

1- How JavaScript functions actually work:

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");

There are some crucial points that we have to consider before going through the prototype concept.

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

Person

do the same exact thing without using prototype and new keyword

So in this step functions, objects and this keyword, are all we have.

this
new
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

Person("George");
getName();//would print the "George" in the console

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

-The easiest way to do this is modifying the empty person object, like:

person.Person = Person;
person.getName = getName;

this way we can call them like:

person.Person("George");
person.getName();// -->"George"
person
Object {Person: function, getName: function, name: "George"}

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

person.__proto__.Person = Person;
person.__proto__.getName = getName;

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

person.__proto__ = {
    Person: Person,
    getName: getName
};

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

console.log(person.__proto__===propertiesObject); //true

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

as you see using any of these two way this would exactly point to the person object.

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

and

The call() method calls a function with a given this value and arguments provided individually.

this way which is my favorite, we can easily call our functions like:

Person.call(person, "George");
//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

var newObject = {};

we have my_person_prototype here similar to the prototype object.

for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
getName
my_person_prototype
newObject.getName();

we can do this with our sample like:

Person.call(newObject, "George");
Person.apply(newObject, ["George"]);

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

now the end result before simulating the other steps: Object {name: "George"}

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

new FunctionName()

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

console.log(Object.prototype.__proto__===null);//true

and that's how inheritance works in JavaScript.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

+1 for the illustration at the end of your "book" :)

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 980

Explicitly set this of the callback - part 1

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes, like other variables. Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`
this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

It might look like you have no control over the value of this because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behaviour as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

ECMAScript 6 introduces arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behaviour they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.

Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the body is clicked, the value logged will be undefined, because inside the event handler, this refers to the body, not the instance of Foo. As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined. If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function has callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};
document.body.onclick = () => this.method();

Felix, I've read to this answer before but never replied. I grow concerned that people use self and that to refer to this. I feel this way because this is an overloaded variable used in different contexts; whereas self usually corresponds to the local instance and that usually refers to another object. I know you did not set this rule, as I've seen it appear in a number of other places, but it is also why I've started to use _this, but am not sure how others feel, except for the non-uniform practice that has resulted.

$(...).on('click', $.proxy(obj, 'function'))
$(...).off('click', obj.function)

@FelixKling would it be safe to assume that using this inside prototype functions will always have the expected behaviour regardless how they are (typically) called? When using callbacks inside prototype functions, is there an alternative to bind(), self or that?

@FelixKling It can be useful at times to rely on Function.prototype.call () and Function.prototype.apply (). Particularly with apply () I've gotten a lot of mileage. I am less inclined to use bind () perhaps only out of habit though I am aware ( but not certain ) that there may be slight overhead advantages to using bind over the other options.

Great answer but consider adding an additional optional solution which is just to not use classes, new, or this at all.

javascript - How to access the correct `this` inside a callback? - Sta...

javascript callback this
Rectangle 27 479

Prototypal Inheritance in JavaScript

I know that this answer is 3 years late but I really think the current answers do not provide enough information about how prototypal inheritance is better than classical inheritance.

First let's see the most common arguments JavaScript programmers state in defence of prototypal inheritance (I'm taking these arguments from the current pool of answers):

Now these arguments are all valid, but nobody has bothered explaining why. It's like telling a child that studying Maths is important. Sure it is, but the child certainly doesn't care; and you can't make a child like Maths by saying that it's important.

I think the problem with prototypal inheritance is that it's explained from the perspective of JavaScript. I love JavaScript, but prototypal inheritance in JavaScript is wrong. Unlike classical inheritance there are two patterns of prototypal inheritance:

  • The prototypal pattern of prototypal inheritance.
  • The constructor pattern of prototypal inheritance.

Unfortunately JavaScript uses the constructor pattern of prototypal inheritance. This is because when JavaScript was created, Brendan Eich (the creator of JS) wanted it to look like Java (which has classical inheritance):

And we were pushing it as a little brother to Java, as a complementary language like Visual Basic was to C++ in Microsofts language families at the time.

This is bad because when people use constructors in JavaScript they think of constructors inheriting from other constructors. This is wrong. In prototypal inheritance objects inherit from other objects. Constructors never come into the picture. This is what confuses most people.

People from languages like Java, which has classical inheritance, get even more confused because although constructors look like classes they don't behave like classes. As Douglas Crockford stated:

This indirection was intended to make the language seem more familiar to classically trained programmers, but failed to do that, as we can see from the very low opinion Java programmers have of JavaScript. JavaScripts constructor pattern did not appeal to the classical crowd. It also obscured JavaScripts true prototypal nature. As a result, there are very few programmers who know how to use the language effectively.

There you have it. Straight from the horse's mouth.

Prototypal inheritance is all about objects. Objects inherit properties from other objects. That's all there is to it. There are two ways of creating objects using prototypal inheritance:

  • Create a brand new object.
  • Clone an existing object and extend it.

Note: JavaScript offers two ways to clone an object - delegation and concatenation. Henceforth I'll use the word "clone" to exclusively refer to inheritance via delegation, and the word "copy" to exclusively refer to inheritance via concatenation.

Enough talk. Let's see some examples. Say I have a circle of radius 5:

var circle = {
    radius: 5
};

We can calculate the area and the circumference of the circle from its radius:

circle.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

circle.circumference = function () {
    return 2 * Math.PI * this.radius;
};

Now I want to create another circle of radius 10. One way to do this would be:

var circle2 = {
    radius: 10,
    area: circle.area,
    circumference: circle.circumference
};

However JavaScript provides a better way - delegation. Crockford's Object.create function is used to do this:

var circle2 = Object.create(circle);
circle2.radius = 10;

That's all. You just did prototypal inheritance in JavaScript. Wasn't that simple? You take an object, clone it, change whatever you need to, and hey presto - you got yourself a brand new object.

Now you might ask, "How is this simple? Every time I want to create a new circle I need to clone circle and manually assign it a radius". Well the solution is to use a function to do the heavy lifting for you:

function createCircle(radius) {
    var newCircle = Object.create(circle);
    newCircle.radius = radius;
    return newCircle;
}

var circle2 = createCircle(10);

In fact you can combine all of this into a single object literal as follows:

var circle = {
    radius: 5,
    create: function (radius) {
        var circle = Object.create(this);
        circle.radius = radius;
        return circle;
    },
    area: function () {
        var radius = this.radius;
        return Math.PI * radius * radius;
    },
    circumference: function () {
        return 2 * Math.PI * this.radius;
    }
};

var circle2 = circle.create(10);

If you notice in the above program the create function creates a clone of circle, assigns a new radius to it and then returns it. This is exactly what a constructor does in JavaScript:

function Circle(radius) {
    this.radius = radius;
}

Circle.prototype.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

Circle.prototype.circumference = function () {         
    return 2 * Math.PI * this.radius;
};

var circle = new Circle(5);
var circle2 = new Circle(10);

The constructor pattern in JavaScript is the prototypal pattern inverted. Instead of creating an object you create a constructor. The new keyword binds the this pointer inside the constructor to a clone of the prototype of the constructor.

Sounds confusing? It's because the constructor pattern in JavaScript unnecessarily complicates things. This is what most programmers find difficult to understand.

Instead of thinking of objects inheriting from other objects they think of constructors inheriting from other constructors and then become utterly confused.

There's a whole bunch of other reasons why the constructor pattern in JavaScript should be avoided. You can read about them in my blog post here: Constructors vs Prototypes

So what are the benefits of prototypal inheritance over classical inheritance? Let's go through the most common arguments again, and explain why.

In my opinion the major benefit of prototypal inheritance is its simplicity.

Let's consider what we just did. We created an object circle which had a radius of 5. Then we cloned it and gave the clone a radius of 10.

Hence we only need two things to make prototypal inheritance work:

Object.create

You get the idea. The point is that prototypal inheritance is easier to understand, easier to implement, and easier to reason about.

As Steve Yegge puts it in his classical blog post "Portrait of a N00b":

Metadata is any kind of description or model of something else. The comments in your code are just a a natural-language description of the computation. What makes metadata meta-data is that it's not strictly necessary. If I have a dog with some pedigree paperwork, and I lose the paperwork, I still have a perfectly valid dog.

In the same sense classes are just meta-data. Classes aren't strictly required for inheritance. However some people (usually n00bs) find classes more comfortable to work with. It gives them a false sense of security.

Well, we also know that static types are just metadata. They're a specialized kind of comment targeted at two kinds of readers: programmers and compilers. Static types tell a story about the computation, presumably to help both reader groups understand the intent of the program. But the static types can be thrown away at runtime, because in the end they're just stylized comments. They're like pedigree paperwork: it might make a certain insecure personality type happier about their dog, but the dog certainly doesn't care.

As I stated earlier, classes give people a false sense of security. For example you get too many NullPointerExceptions in Java even when your code is perfectly legible. I find classical inheritance usually gets in the way of programming, but maybe that's just Java. Python has an amazing classical inheritance system.

Most programmers who come from a classical background argue that classical inheritance is more powerful than prototypal inheritance because it has:

This claim is false. We already know that JavaScript supports private variables via closures, but what about multiple inheritance? Objects in JavaScript only have one prototype.

The truth is that prototypal inheritance supports inheriting from multiple prototypes. Prototypal inheritance simply means one object inheriting from another object. There are actually two ways to implement prototypal inheritance:

Yes JavaScript only allows objects to delegate to one other object. However it allows you to copy the properties of an arbitrary number of objects. For example _.extend does just this.

Of course many programmers don't consider this to be true inheritance because instanceof and isPrototypeOf say otherwise. However this can be easily remedied by storing an array of prototypes on every object which inherits from a prototype via concatenation:

function copyOf(object, prototype) {
    var prototypes = object.prototypes;
    var prototypeOf = Object.isPrototypeOf;
    return prototypes.indexOf(prototype) >= 0 ||
        prototypes.some(prototypeOf, prototype);
}

Hence prototypal inheritance is just as powerful as classical inheritance. In fact it's much more powerful than classical inheritance because in prototypal inheritance you can hand pick which properties to copy and which properties to omit from different prototypes.

In classical inheritance it's impossible (or at least very difficult) to choose which properties you want to inherit. They use virtual base classes and interfaces to solve the diamond problem.

In JavaScript however you'll most likely never hear of the diamond problem because you can control exactly which properties you wish to inherit and from which prototypes.

This point is a little more difficult to explain because classical inheritance doesn't necessarily lead to more redundant code. In fact inheritance, whether classical or prototypal, is used to reduce the redundancy in code.

One argument could be that most programming languages with classical inheritance are statically typed and require the user to explicitly declare types (unlike Haskell which has implicit static typing). Hence this leads to more verbose code.

Java is notorious for this behavior. I distinctly remember Bob Nystrom mentioning the following anecdote in his blog post about Pratt Parsers:

You gotta love Java's "please sign it in quadruplicate" level of bureaucracy here.

One valid argument is that not all languages which have classical inheritance support multiple inheritance. Again Java comes to mind. Yes Java has interfaces, but that's not sufficient. Sometimes you really need multiple inheritance.

Since prototypal inheritance allows for multiple inheritance, code which requires multiple inheritance is less redundant if written using prototypal inheritance rather than in a language which has classical inheritance but no multiple inheritance.

One of the most important advantages of prototypal inheritance is that you can add new properties to prototypes after they are created. This allows you to add new methods to a prototype which will be automatically made available to all the objects which delegate to that prototype.

This is not possible in classical inheritance because once a class is created you can't modify it at runtime. This is probably the single biggest advantage of prototypal inheritance over classical inheritance, and it should have been at the top. However I like saving the best for the end.

Prototypal inheritance matters. It's important to educate JavaScript programmers on why to abandon the constructor pattern of prototypal inheritance in favor of the prototypal pattern of prototypal inheritance.

We need to start teaching JavaScript correctly and that means showing new programmers how to write code using the prototypal pattern instead of the constructor pattern.

Not only will it be it easier to explain prototypal inheritance using the prototypal pattern, but it will also make better programmers.

While I understand where you are coming from, and I agree that prototypal inheritance is very useful, I think by making the assumption "prototypal inheritance is better than classical inheritance" you are already destined to fail. To give you some perspective, my library jTypes is a classical inheritance library for JavaScript. So being a guy that took the time to make that, I will still sit here and say prototypal inheritance is awesome and very useful. But it is simply just one tool amongst many that a programmer has. There are still many disadvantages to prototypal inheritance as well.

I completely agree with what you said. I feel that too many programmers reject JavaScript for its lack of classical inheritance, or denounce it as a simple and dumb language. It is actually an extremely powerful concept, I agree, and many programmers should accept it and learn it. With that being said, I also feel there are a significant number of developers in JavaScript that oppose any form of classical inheritance all together being in JavaScript, when they really have no basis for their arguments at all. Both are equally powerful in their own right, and equally useful as well.

Well that is your opinion, but I will continue to disagree, and I think the growing popularity of things such as CoffeeScript and TypeScript show that there is a large community of developers who would like to utilize this functionality when appropriate. As you said, ES6 adds syntactic sugar, but still does not offer the extensiveness of jTypes. On a side note, I am not the one responsible for your downvote. While I disagree with you, I do not feel it constitutes you having a bad answer. You were very thorough.

You are using word clone a lot, which is simply wrong. Object.create is creating new object with the specified prototype. Your choosing of words give impression that the prototype gets cloned.

@Aadit: there's really no need to be so defensive. Your answer is very detailed and deserving of votes. I wasn't suggesting that "linked" should be a drop-in replacement for "clone", but that it more appropriately describes the connection between an object and the prototype it inherits from, whether you assert your own definition of the term "clone" or not. Change it or don't change it, it's entirely your choice.

javascript - Benefits of prototypal inheritance over classical? - Stac...

javascript oop inheritance language-design prototype-programming
Rectangle 27 472

Prototypal Inheritance in JavaScript

I know that this answer is 3 years late but I really think the current answers do not provide enough information about how prototypal inheritance is better than classical inheritance.

First let's see the most common arguments JavaScript programmers state in defence of prototypal inheritance (I'm taking these arguments from the current pool of answers):

Now these arguments are all valid, but nobody has bothered explaining why. It's like telling a child that studying Maths is important. Sure it is, but the child certainly doesn't care; and you can't make a child like Maths by saying that it's important.

I think the problem with prototypal inheritance is that it's explained from the perspective of JavaScript. I love JavaScript, but prototypal inheritance in JavaScript is wrong. Unlike classical inheritance there are two patterns of prototypal inheritance:

  • The prototypal pattern of prototypal inheritance.
  • The constructor pattern of prototypal inheritance.

Unfortunately JavaScript uses the constructor pattern of prototypal inheritance. This is because when JavaScript was created, Brendan Eich (the creator of JS) wanted it to look like Java (which has classical inheritance):

And we were pushing it as a little brother to Java, as a complementary language like Visual Basic was to C++ in Microsofts language families at the time.

This is bad because when people use constructors in JavaScript they think of constructors inheriting from other constructors. This is wrong. In prototypal inheritance objects inherit from other objects. Constructors never come into the picture. This is what confuses most people.

People from languages like Java, which has classical inheritance, get even more confused because although constructors look like classes they don't behave like classes. As Douglas Crockford stated:

This indirection was intended to make the language seem more familiar to classically trained programmers, but failed to do that, as we can see from the very low opinion Java programmers have of JavaScript. JavaScripts constructor pattern did not appeal to the classical crowd. It also obscured JavaScripts true prototypal nature. As a result, there are very few programmers who know how to use the language effectively.

There you have it. Straight from the horse's mouth.

Prototypal inheritance is all about objects. Objects inherit properties from other objects. That's all there is to it. There are two ways of creating objects using prototypal inheritance:

  • Create a brand new object.
  • Clone an existing object and extend it.

Note: JavaScript offers two ways to clone an object - delegation and concatenation. Henceforth I'll use the word "clone" to exclusively refer to inheritance via delegation, and the word "copy" to exclusively refer to inheritance via concatenation.

Enough talk. Let's see some examples. Say I have a circle of radius 5:

var circle = {
    radius: 5
};

We can calculate the area and the circumference of the circle from its radius:

circle.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

circle.circumference = function () {
    return 2 * Math.PI * this.radius;
};

Now I want to create another circle of radius 10. One way to do this would be:

var circle2 = {
    radius: 10,
    area: circle.area,
    circumference: circle.circumference
};

However JavaScript provides a better way - delegation. Crockford's Object.create function is used to do this:

var circle2 = Object.create(circle);
circle2.radius = 10;

That's all. You just did prototypal inheritance in JavaScript. Wasn't that simple? You take an object, clone it, change whatever you need to, and hey presto - you got yourself a brand new object.

Now you might ask, "How is this simple? Every time I want to create a new circle I need to clone circle and manually assign it a radius". Well the solution is to use a function to do the heavy lifting for you:

function createCircle(radius) {
    var newCircle = Object.create(circle);
    newCircle.radius = radius;
    return newCircle;
}

var circle2 = createCircle(10);

In fact you can combine all of this into a single object literal as follows:

var circle = {
    radius: 5,
    create: function (radius) {
        var circle = Object.create(this);
        circle.radius = radius;
        return circle;
    },
    area: function () {
        var radius = this.radius;
        return Math.PI * radius * radius;
    },
    circumference: function () {
        return 2 * Math.PI * this.radius;
    }
};

var circle2 = circle.create(10);

If you notice in the above program the create function creates a clone of circle, assigns a new radius to it and then returns it. This is exactly what a constructor does in JavaScript:

function Circle(radius) {
    this.radius = radius;
}

Circle.prototype.area = function () {
    var radius = this.radius;
    return Math.PI * radius * radius;
};

Circle.prototype.circumference = function () {         
    return 2 * Math.PI * this.radius;
};

var circle = new Circle(5);
var circle2 = new Circle(10);

The constructor pattern in JavaScript is the prototypal pattern inverted. Instead of creating an object you create a constructor. The new keyword binds the this pointer inside the constructor to a clone of the prototype of the constructor.

Sounds confusing? It's because the constructor pattern in JavaScript unnecessarily complicates things. This is what most programmers find difficult to understand.

Instead of thinking of objects inheriting from other objects they think of constructors inheriting from other constructors and then become utterly confused.

There's a whole bunch of other reasons why the constructor pattern in JavaScript should be avoided. You can read about them in my blog post here: Constructors vs Prototypes

So what are the benefits of prototypal inheritance over classical inheritance? Let's go through the most common arguments again, and explain why.

In my opinion the major benefit of prototypal inheritance is its simplicity.

Let's consider what we just did. We created an object circle which had a radius of 5. Then we cloned it and gave the clone a radius of 10.

Hence we only need two things to make prototypal inheritance work:

Object.create

You get the idea. The point is that prototypal inheritance is easier to understand, easier to implement, and easier to reason about.

As Steve Yegge puts it in his classical blog post "Portrait of a N00b":

Metadata is any kind of description or model of something else. The comments in your code are just a a natural-language description of the computation. What makes metadata meta-data is that it's not strictly necessary. If I have a dog with some pedigree paperwork, and I lose the paperwork, I still have a perfectly valid dog.

In the same sense classes are just meta-data. Classes aren't strictly required for inheritance. However some people (usually n00bs) find classes more comfortable to work with. It gives them a false sense of security.

Well, we also know that static types are just metadata. They're a specialized kind of comment targeted at two kinds of readers: programmers and compilers. Static types tell a story about the computation, presumably to help both reader groups understand the intent of the program. But the static types can be thrown away at runtime, because in the end they're just stylized comments. They're like pedigree paperwork: it might make a certain insecure personality type happier about their dog, but the dog certainly doesn't care.

As I stated earlier, classes give people a false sense of security. For example you get too many NullPointerExceptions in Java even when your code is perfectly legible. I find classical inheritance usually gets in the way of programming, but maybe that's just Java. Python has an amazing classical inheritance system.

Most programmers who come from a classical background argue that classical inheritance is more powerful than prototypal inheritance because it has:

This claim is false. We already know that JavaScript supports private variables via closures, but what about multiple inheritance? Objects in JavaScript only have one prototype.

The truth is that prototypal inheritance supports inheriting from multiple prototypes. Prototypal inheritance simply means one object inheriting from another object. There are actually two ways to implement prototypal inheritance:

Yes JavaScript only allows objects to delegate to one other object. However it allows you to copy the properties of an arbitrary number of objects. For example _.extend does just this.

Of course many programmers don't consider this to be true inheritance because instanceof and isPrototypeOf say otherwise. However this can be easily remedied by storing an array of prototypes on every object which inherits from a prototype via concatenation:

function copyOf(object, prototype) {
    var prototypes = object.prototypes;
    var prototypeOf = Object.isPrototypeOf;
    return prototypes.indexOf(prototype) >= 0 ||
        prototypes.some(prototypeOf, prototype);
}

Hence prototypal inheritance is just as powerful as classical inheritance. In fact it's much more powerful than classical inheritance because in prototypal inheritance you can hand pick which properties to copy and which properties to omit from different prototypes.

In classical inheritance it's impossible (or at least very difficult) to choose which properties you want to inherit. They use virtual base classes and interfaces to solve the diamond problem.

In JavaScript however you'll most likely never hear of the diamond problem because you can control exactly which properties you wish to inherit and from which prototypes.

This point is a little more difficult to explain because classical inheritance doesn't necessarily lead to more redundant code. In fact inheritance, whether classical or prototypal, is used to reduce the redundancy in code.

One argument could be that most programming languages with classical inheritance are statically typed and require the user to explicitly declare types (unlike Haskell which has implicit static typing). Hence this leads to more verbose code.

Java is notorious for this behavior. I distinctly remember Bob Nystrom mentioning the following anecdote in his blog post about Pratt Parsers:

You gotta love Java's "please sign it in quadruplicate" level of bureaucracy here.

One valid argument is that not all languages which have classical inheritance support multiple inheritance. Again Java comes to mind. Yes Java has interfaces, but that's not sufficient. Sometimes you really need multiple inheritance.

Since prototypal inheritance allows for multiple inheritance, code which requires multiple inheritance is less redundant if written using prototypal inheritance rather than in a language which has classical inheritance but no multiple inheritance.

One of the most important advantages of prototypal inheritance is that you can add new properties to prototypes after they are created. This allows you to add new methods to a prototype which will be automatically made available to all the objects which delegate to that prototype.

This is not possible in classical inheritance because once a class is created you can't modify it at runtime. This is probably the single biggest advantage of prototypal inheritance over classical inheritance, and it should have been at the top. However I like saving the best for the end.

Prototypal inheritance matters. It's important to educate JavaScript programmers on why to abandon the constructor pattern of prototypal inheritance in favor of the prototypal pattern of prototypal inheritance.

We need to start teaching JavaScript correctly and that means showing new programmers how to write code using the prototypal pattern instead of the constructor pattern.

Not only will it be it easier to explain prototypal inheritance using the prototypal pattern, but it will also make better programmers.

While I understand where you are coming from, and I agree that prototypal inheritance is very useful, I think by making the assumption "prototypal inheritance is better than classical inheritance" you are already destined to fail. To give you some perspective, my library jTypes is a classical inheritance library for JavaScript. So being a guy that took the time to make that, I will still sit here and say prototypal inheritance is awesome and very useful. But it is simply just one tool amongst many that a programmer has. There are still many disadvantages to prototypal inheritance as well.

I completely agree with what you said. I feel that too many programmers reject JavaScript for its lack of classical inheritance, or denounce it as a simple and dumb language. It is actually an extremely powerful concept, I agree, and many programmers should accept it and learn it. With that being said, I also feel there are a significant number of developers in JavaScript that oppose any form of classical inheritance all together being in JavaScript, when they really have no basis for their arguments at all. Both are equally powerful in their own right, and equally useful as well.

Well that is your opinion, but I will continue to disagree, and I think the growing popularity of things such as CoffeeScript and TypeScript show that there is a large community of developers who would like to utilize this functionality when appropriate. As you said, ES6 adds syntactic sugar, but still does not offer the extensiveness of jTypes. On a side note, I am not the one responsible for your downvote. While I disagree with you, I do not feel it constitutes you having a bad answer. You were very thorough.

You are using word clone a lot, which is simply wrong. Object.create is creating new object with the specified prototype. Your choosing of words give impression that the prototype gets cloned.

@Aadit: there's really no need to be so defensive. Your answer is very detailed and deserving of votes. I wasn't suggesting that "linked" should be a drop-in replacement for "clone", but that it more appropriately describes the connection between an object and the prototype it inherits from, whether you assert your own definition of the term "clone" or not. Change it or don't change it, it's entirely your choice.

javascript - Benefits of prototypal inheritance over classical? - Stac...

javascript oop inheritance language-design prototype-programming
Rectangle 27 192

Read more... about the Vanilla JavaScript solution.

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})
location.(search|hash)
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined
(item in dict) ? dict.item.push(val) : dict.item = [val]

arrays

qd.key[index]
qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dstle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=stle&car=saab"]
decodeURIComponent(undefined)
"undefined"
&&
decodeURIComponent()
v = v && decodeURIComponent(v);

If the querystring is empty (location.search == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if (location.search) location.search.substr(1).split("&").forEach(...)

Nice. The only thing I would change - is if there aren't more than one values for a key there is no need for it to be an array. Only use array if there is more than one value per key.

@PavelNikolov I think it would introduce difficulties getting sometimes an array and sometimes a value. You would have to check for it first, now you only check the length, because you will be using cycles for retrieving those values anyways. Also this was meant to be the easiest, but functional, solution here.

@twig will not work in IE8

Flattened out a bit for readability, made into a function, and re-used split call: function parseQueryString() { var qd = {}; location.search.substr(1).split("&").forEach(function(item) { var parts = item.split("="); var k = parts[0]; var v = decodeURIComponent(parts[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,] }); return qd; }

var qd = {}; location.search.substr(1).split("&").forEach(   function(item) {     var s = item.split("="),       k = s[0], v;     if(s.length>1)       v = decodeURIComponent(s[1]);     (k in qd) ? qd[k].push(v) : qd[k] = [v]   })

url - How can I get query string values in JavaScript? - Stack Overflo...

javascript url plugins query-string
Rectangle 27 192

Read more... about the Vanilla JavaScript solution.

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})
location.(search|hash)
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined
(item in dict) ? dict.item.push(val) : dict.item = [val]

arrays

qd.key[index]
qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dstle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=stle&car=saab"]
decodeURIComponent(undefined)
"undefined"
&&
decodeURIComponent()
v = v && decodeURIComponent(v);

If the querystring is empty (location.search == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if (location.search) location.search.substr(1).split("&").forEach(...)

Nice. The only thing I would change - is if there aren't more than one values for a key there is no need for it to be an array. Only use array if there is more than one value per key.

@PavelNikolov I think it would introduce difficulties getting sometimes an array and sometimes a value. You would have to check for it first, now you only check the length, because you will be using cycles for retrieving those values anyways. Also this was meant to be the easiest, but functional, solution here.

@twig will not work in IE8

Flattened out a bit for readability, made into a function, and re-used split call: function parseQueryString() { var qd = {}; location.search.substr(1).split("&").forEach(function(item) { var parts = item.split("="); var k = parts[0]; var v = decodeURIComponent(parts[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,] }); return qd; }

var qd = {}; location.search.substr(1).split("&").forEach(   function(item) {     var s = item.split("="),       k = s[0], v;     if(s.length>1)       v = decodeURIComponent(s[1]);     (k in qd) ? qd[k].push(v) : qd[k] = [v]   })

url - How can I get query string values in JavaScript? - Stack Overflo...

javascript url plugins query-string
Rectangle 27 192

Read more... about the Vanilla JavaScript solution.

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})
location.(search|hash)
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined
(item in dict) ? dict.item.push(val) : dict.item = [val]

arrays

qd.key[index]
qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dstle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=stle&car=saab"]
decodeURIComponent(undefined)
"undefined"
&&
decodeURIComponent()
v = v && decodeURIComponent(v);

If the querystring is empty (location.search == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if (location.search) location.search.substr(1).split("&").forEach(...)

Nice. The only thing I would change - is if there aren't more than one values for a key there is no need for it to be an array. Only use array if there is more than one value per key.

@PavelNikolov I think it would introduce difficulties getting sometimes an array and sometimes a value. You would have to check for it first, now you only check the length, because you will be using cycles for retrieving those values anyways. Also this was meant to be the easiest, but functional, solution here.

@twig will not work in IE8

Flattened out a bit for readability, made into a function, and re-used split call: function parseQueryString() { var qd = {}; location.search.substr(1).split("&").forEach(function(item) { var parts = item.split("="); var k = parts[0]; var v = decodeURIComponent(parts[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,] }); return qd; }

var qd = {}; location.search.substr(1).split("&").forEach(   function(item) {     var s = item.split("="),       k = s[0], v;     if(s.length>1)       v = decodeURIComponent(s[1]);     (k in qd) ? qd[k].push(v) : qd[k] = [v]   })

url - How can I get query string values in JavaScript? - Stack Overflo...

javascript url plugins query-string
Rectangle 27 27

Getters and Setters in JavaScript

Getters and setters in JavaScript are used for defining computed properties, or accessors. A computed property is one that uses a function to get or set an object value. The basic theory is doing something like this:

var user = { /* ... object with getters and setters ... */ };
user.phone = '+1 (123) 456-7890'; // updates a database
console.log( user.areaCode ); // displays '123'
console.log( user.area ); // displays 'Anytown, USA'

This is useful for automatically doing things behind-the-scenes when a property is accessed, like keeping numbers in range, reformatting strings, triggering value-has-changed events, updating relational data, providing access to private properties, and more.

The examples below show the basic syntax, though they simply get and set the internal object value without doing anything special. In real-world cases you would modify the input and/or output value to suit your needs, as noted above.

ECMAScript 5 supports get and set keywords for defining computed properties. They work with all modern browsers except IE 8 and below.

var foo = {
    bar : 123,
    get bar(){ return bar; },
    set bar( value ){ this.bar = value; }
};
foo.bar = 456;
var gaz = foo.bar;

get and set aren't reserved words, so they can be overloaded to create your own custom, cross-browser computed property functions. This will work in any browser.

var foo = {
    _bar : 123,
    get : function( name ){ return this[ '_' + name ]; },
    set : function( name, value ){ this[ '_' + name ] = value; }
};
foo.set( 'bar', 456 );
var gaz = foo.get( 'bar' );

Or for a more compact approach, a single function may be used.

var foo = {
    _bar : 123,
    value : function( name /*, value */ ){
        if( arguments.length < 2 ){ return this[ '_' + name ]; }
        this[ '_' + name ] = value;
    }
};
foo.value( 'bar', 456 );
var gaz = foo.value( 'bar' );

Avoid doing something like this, which can lead to code bloat.

var foo = {
    _a : 123, _b : 456, _c : 789,
    getA : function(){ return this.bar; },
    getB : ..., getC : ..., setA : ..., setB : ..., setC : ...
};

For the above examples, the internal property names are abstracted with an underscore in order to discourage users from simply doing foo.bar vs. foo.get( 'bar' ) and getting an "uncooked" value. You can use conditional code to do different things depending on the name of the property being accessed (via the name parameter).

Using Object.defineProperty() is another way to add getters and setters, and can be used on objects after they're defined. It can also be used to set configurable and enumerable behaviors. This syntax also works with IE 8, but unfortunately only on DOM objects.

var foo = { bar : 123 };
Object.defineProperty( foo, 'bar', {
    get : function(){ return bar; },
    set : function( value ){ this.bar = value; }
} );
foo.bar = 456;
var gaz = foo.bar;

Finally, __defineGetter__() is another option. It's deprecated, but still widely used around the web and thus unlikely to disappear anytime soon. It works on all browsers except IE 10 and below. Though the other options also work well on non-IE, so this one isn't that useful.

var foo = { bar : 123; }
foo.__defineGetter__( 'bar', function(){ return this.bar; } );
foo.__defineSetter__( 'bar', function( value ){ this.bar = value; } );
this[ '_' + name ] = value;
this[ '_' + name ] = arguments[1];
value

Javascript getters and setters for dummies? - Stack Overflow

javascript setter getter
Rectangle 27 23

Solution with no JavaScript

This uses CSS pseudo hover to set the display of the hidden element. The display none needs to be in the style and not on the element so it can be overwritten in the hover.

<div class="couponcode">First Link
    <span class="coupontooltip">Content 1</span> <!-- UPDATED -->
</div>

<div class="couponcode">Second Link
    <span class="coupontooltip"> Content 2</span> <!-- UPDATED -->
</div>
.couponcode:hover .coupontooltip { /* NEW */
    display: block;
}


.coupontooltip {
    display: none;  /* NEW */
    background: #C8C8C8;
    margin-left: 28px;
    padding: 10px;
    position: absolute;
    z-index: 1000;
    width:200px;
    height:100px;
}

.couponcode {
    margin:100px;
}

If you need to support really old browsers, you would need to add a class to the outside element when the mouse enters the div. And remove that class when mouse leaves.

Your code did not work because what is tp? Is a collection of elements and you are treating it as one. What you would need to do is pass in the reference to the element

<div class = "name" onmouseover="show(this)" onmouseout="hide(this)">  <!-- added "this" 2 times -->
//var name = document.getElementsByclassName("name");  /* not needed */
//    var tp = document.getElementsByclassName("tooltip"); /* not needed */


function show (elem) {  /* added argument */
    elem.style.display="block"; /* changed variable to argument */
}
function hide (elem) { /* added argument */
    elem.style.display="";  /* changed variable to argument */
}

will this help if i wanted to get contents from database using ajax inside tooltip

and JS would be nice. can you tell why my code didn't work

I just updated the tooltip with easing: jsfiddle.net/q46Xz/195

:hover>.coupontooltip would let you put tooltips inside of anything.

Plain Javascript Tooltip - Stack Overflow

javascript tooltip