Rectangle 27 56

After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts

and

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

It would be great if you could provide a short abstract of the contents of the links so this answer is still usefull when the links are dead.

thats a clear chart ? :)

[[Prototype]]

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 56

After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts

and

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

It would be great if you could provide a short abstract of the contents of the links so this answer is still usefull when the links are dead.

thats a clear chart ? :)

[[Prototype]]

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 56

After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts

and

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

It would be great if you could provide a short abstract of the contents of the links so this answer is still usefull when the links are dead.

thats a clear chart ? :)

[[Prototype]]

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 56

After reading this thread, I feel confused with JavaScript Prototype Chain, then I found these charts

and

prototype chain can be technically extended as long as you want, each time by setting the prototype of the subclass equal to an object of the parent class.

It would be great if you could provide a short abstract of the contents of the links so this answer is still usefull when the links are dead.

thats a clear chart ? :)

[[Prototype]]

How does JavaScript .prototype work? - Stack Overflow

javascript prototype-oriented
Rectangle 27 79

I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.

There are three options to define the scope of a directive:

  • scope: false: Angular default. The directive's scope is exactly the one of its parent scope (parentScope).
  • scope: true: Angular creates a scope for this directive. The scope prototypically inherits from parentScope.
scope: {...}
isolatedScope.$parent === parentScope
app.directive("myDirective", function() {
    return {
        scope: {
            ... // defining scope means that 'no inheritance from parent'.
        },
    }
})
isolatedScope
parentScope

The topic about using symbols @, = and & are talking about scenarios using isolatedScope

It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.

Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:

@ simply passes the property from parentScope to isolatedScope. It is called one-way binding, which means you cannot modify the value of parentScope properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:

If the binding property is a primitive type, like interpolatedProp in the example: you can modify interpolatedProp, but parentProp1 would not be changed. However, if you change the value of parentProp1, interpolatedProp will be overwritten with the new value (when angular $digest).

If the binding property is some object, like parentObj: since the one passed to isolatedScope is a reference, modifying the value will trigger this error:

TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

= is called two-way binding, which means any modification in childScope will also update the value in parentScope, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj to be =, you will find that you can modify the value of parentObj.x. A typical example is ngModel.

& allows the directive to call some parentScope function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.

Define a clickable template in the directive like:

<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">

And use the directive like:

<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>

The variable valueFromDirective is passed from the directive to the parent controller through {valueFromDirective: ....

By default, directives use shared scope. If directive has 'scope:true', then it uses inherited scope, in which child can see parent properties but parent cannot see child internal properties.

javascript - What is the difference between & vs @ and = in angularJS ...

javascript angularjs
Rectangle 27 78

I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.

There are three options to define the scope of a directive:

  • scope: false: Angular default. The directive's scope is exactly the one of its parent scope (parentScope).
  • scope: true: Angular creates a scope for this directive. The scope prototypically inherits from parentScope.
scope: {...}
isolatedScope.$parent === parentScope
app.directive("myDirective", function() {
    return {
        scope: {
            ... // defining scope means that 'no inheritance from parent'.
        },
    }
})
isolatedScope
parentScope

The topic about using symbols @, = and & are talking about scenarios using isolatedScope

It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.

Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:

@ simply passes the property from parentScope to isolatedScope. It is called one-way binding, which means you cannot modify the value of parentScope properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:

If the binding property is a primitive type, like interpolatedProp in the example: you can modify interpolatedProp, but parentProp1 would not be changed. However, if you change the value of parentProp1, interpolatedProp will be overwritten with the new value (when angular $digest).

If the binding property is some object, like parentObj: since the one passed to isolatedScope is a reference, modifying the value will trigger this error:

TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

= is called two-way binding, which means any modification in childScope will also update the value in parentScope, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj to be =, you will find that you can modify the value of parentObj.x. A typical example is ngModel.

& allows the directive to call some parentScope function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.

Define a clickable template in the directive like:

<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">

And use the directive like:

<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>

The variable valueFromDirective is passed from the directive to the parent controller through {valueFromDirective: ....

By default, directives use shared scope. If directive has 'scope:true', then it uses inherited scope, in which child can see parent properties but parent cannot see child internal properties.

javascript - What is the difference between & vs @ and = in angularJS ...

javascript angularjs
Rectangle 27 166

Since the canvas isn't always styled relative to the entire page, the canvas.offsetLeft/Top doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a div element containing the canvas with a position: relative style applied. To account for this you need to loop through the chain of offsetParents, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all.

function relMouseCoords(event){
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do{
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    }
    while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is

coords = canvas.relMouseCoords(event);
canvasX = coords.x;
canvasY = coords.y;

No, it is using the builtin javascript prototype object --- developer.mozilla.org/en/

event.offsetX
event.offsetY
if (event.offsetX !== undefined && event.offsetY !== undefined) { return {x:event.offsetX, y:event.offsetY}; }

Baczek is correct about Chrome's event.offsetX and event.offsetY which also works in IE9. For Firefox (tested w/ v13) you can use event.layerX and event.layerY.

canvasX = event.pageX - totalOffsetX - document.body.scrollLeft; canvasY = event.pageY - totalOffsetY - document.body.scrollTop;

This final version on answer didn't work for me. On Firefox, if whole screen is scrolled, I got the displaced value as output. What worked for me was a very similar solution, given on stackoverflow.com/a/10816667/578749 that instead of event.pageX/Y, it subtracted calculated offset from event.clientX/Y. Could someone review this and explain?

javascript - How do I get the coordinates of a mouse click on a canvas...

javascript canvas
Rectangle 27 129

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes.

myObject.prop = '123';
myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

While this is a very simple concept, it may not be very obvious since, I believe, a lot of people miss it. Well put.

Excellent remark. I take away, the resolution of a non object property doesn't involve a read whereas the resolution of an object property does.

Why? What is the motivation for property writes not going up the prototype chain? It's seems crazy...

@Jonathan. this is in line with how Javascript prototypes work. Your question applies to the design of JS, not of Angular

It would be great if you added a real simple example.

javascript - What are the nuances of scope prototypal / prototypical i...

javascript angularjs inheritance prototype prototypal-inheritance
Rectangle 27 128

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes.

myObject.prop = '123';
myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

While this is a very simple concept, it may not be very obvious since, I believe, a lot of people miss it. Well put.

Excellent remark. I take away, the resolution of a non object property doesn't involve a read whereas the resolution of an object property does.

Why? What is the motivation for property writes not going up the prototype chain? It's seems crazy...

@Jonathan. this is in line with how Javascript prototypes work. Your question applies to the design of JS, not of Angular

It would be great if you added a real simple example.

javascript - What are the nuances of scope prototypal / prototypical i...

javascript angularjs inheritance prototype prototypal-inheritance
Rectangle 27 128

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes.

myObject.prop = '123';
myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

While this is a very simple concept, it may not be very obvious since, I believe, a lot of people miss it. Well put.

Excellent remark. I take away, the resolution of a non object property doesn't involve a read whereas the resolution of an object property does.

Why? What is the motivation for property writes not going up the prototype chain? It's seems crazy...

@Jonathan. this is in line with how Javascript prototypes work. Your question applies to the design of JS, not of Angular

It would be great if you added a real simple example.

javascript - What are the nuances of scope prototypal / prototypical i...

javascript angularjs inheritance prototype prototypal-inheritance
Rectangle 27 5

TLDR-Q1: Can I throw exceptions in constructor methods? What about in javascript prototypes? Why!? How should I handle it?

Yes, you can throw exceptions in a constructor. If truly invalid arguments have been passed, then that is probably the cleanest way to do things.

I, myself, would not generally design an expected path of the code to throw an exception, but would instead reserve it for the type of error that probably signifies bad data or wrong usage by the programmer. Exceptions get logged nice and cleanly in the debug console and are one of the quickest ways to communicate to someone using your constructor that they've messed up as it will get logged and you can put a nice descriptive message in the error object when you throw and the developer gets a stack trace.

Returning null is not such a clean or helpful way and adds code the developer probably doesn't normally need to check for null all the time.

TLDR-Q2: Can I introduce heavy type checking and throw exceptions to give javascript scripts a poor mans static type? Do developers like this? Am I being ignorant and this a really common thing?

You can write Javascript type checking as much as you need. IMO, you should only do so when you're trying to determine if an argument passed in is valid or not. If you need a string and the developer passes in a number and a numeric string is a reasonable input for the function, then I don't see why you should not just use Javascript's string conversion automatically and let things go.

Javascript developers like type checking when it helps them identify a mistake they've made. Javascript developers don't like type checking when it's just being pedantic and an auto or explicit type-conversion would have worked just fine.

Also keep in mind that you should rarely insist that a passed object is a particular type of object (say using instanceof) because it should be perfectly valid to pass any object that works like the expected object. For example, a promise in Javascript can pretty much be any object that has the desired methods that follow the proper specification. It does not have to be one particular type of object class with one particular constructor.

Javascript isn't a strongly typed language and there really is no reason to try to make it behave like it is something that it isn't. Check types when that's required for the proper operation of your code, not because you're trying to make Javascript behave as strictly as Java. I wouldn't suggest adding type checking just because you think all languages should have type checking. If that's your line of thinking, then perhaps you should write in TypeScript or something like that that adds type specification to the language.

Thank you! Super informative and hit all the questions perfectly. I have looked into TypeScript and will play with it more I'm sure, but it does make sense that type checking when it has an explicit purpose and not kicking up a fuss for certain invalid types when they can be cheaply casting it to a valid type. I knew something about "JavaScript is what it is, use it" would come up but this just reiterates the importance of that to me. Thank you again!

class - JavaScript type checking and exceptions in the context of Prot...

javascript class oop prototype
Rectangle 27 8

How to avoid the over-use of the prototype property

As far as I know, JavaScript is a Prototype based language with First-class functions, as you can read here.

Now. Actually this is just a style of OPP wich means you will be working and thinking about objects and inheritance. You just have to know that, in JavaScript, there is no classes but prototypes instead. But remember. It's all about the functions.

To make your own object definition, you would do as follows:

function Animal() {
    this.name = null;
    this.age = 0;
    this.genus = null;
    this.isWild = true;
};

Animal.prototype.hasName = function() {
    return this.name !== null;
};

Animal.prototype.isItWild = function() {
    return this.isWild;
};

// Here we create an instance of Animal
var someAnimal = new Animal();
// Let's give it a name
someAnimal.name = 'Dobby';
console.log('Hey there. My pet name is %s', someAnimal.name);
console.log('is it wild? %o', someAnimal.isWild);

Now you have your Animal prototype. Let's see how to extend its properties to create the Dog prototype:

function Dog() {
    this.genus = 'Canis';
    this.race = 'unknown';
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
    console.log('rrouff!);
};

Let's create a race of dog now:

function SiberianHusky(name, age) {
    this.name = name;
    this.age = age;
    this.race = 'Siberian Husky';
}

SiberianHusky.prototype = Object.create(Dog.prototype);
SiberianHusky.prototype.constructor = SiberianHusky;

// Let's create our Siberian Husky
var myPet = new SiberianHusky('Bobby', 5);
// Aww. It is barking!
myPet.bark();

You can see in the examples that every definition is using the Object prototype. That is used to define how an object is. You can think of it as the class definition.

Instead of writing to the prototype every time, you can do the following:

Animal.prototype = {
    name: null,
    age: 0,
    genus: null,
    isWild: true,
    hasName: function() { ... }
    isItWild: function() { ... }
}

To fully understand the concept of prototypes and how they inherit from each other, you can check this.

This is only one way to work with prototypes. Using object constructors is not at all necessary, and neither is the .prototype property.

I just shared my poor knowledge trying to help. If you can do it better, I encourage you to post an answer instead of a comment. Thanks for the input though.

ecmascript 6 - What to use instead of Classes in JavaScript? - Stack O...

javascript ecmascript-6
Rectangle 27 189

Here are some differences between the two languages:

  • Java is a statically typed language; JavaScript is dynamic.
  • Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.
this

Here are some features that I think are particular strengths of JavaScript:

  • JavaScript supports closures; Java can simulate sort-of "closures" using anonymous classes. (Real closures may be supported in a future version of Java.)
  • JavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.
  • JavaScript allows methods in an object to be redefined independently of its prototype (think eigenclasses in Ruby, but on steroids); methods in a Java object are tied to its class, and cannot be redefined at runtime.

2 years late, but thank you so much for this thoughtful explanation. It's way more useful and informative than the selected answer, and deserves far more votes IMO

I upvote both in such cases. We need the right answer, but holy shmoly, geeks like us we really need more of this humor

You might also here strongly-typed and loosely-typed instead of statically-typed and dynamically-typed.

What's the difference between JavaScript and Java? - Stack Overflow

java javascript
Rectangle 27 189

Here are some differences between the two languages:

  • Java is a statically typed language; JavaScript is dynamic.
  • Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.
this

Here are some features that I think are particular strengths of JavaScript:

  • JavaScript supports closures; Java can simulate sort-of "closures" using anonymous classes. (Real closures may be supported in a future version of Java.)
  • JavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.
  • JavaScript allows methods in an object to be redefined independently of its prototype (think eigenclasses in Ruby, but on steroids); methods in a Java object are tied to its class, and cannot be redefined at runtime.

2 years late, but thank you so much for this thoughtful explanation. It's way more useful and informative than the selected answer, and deserves far more votes IMO

I upvote both in such cases. We need the right answer, but holy shmoly, geeks like us we really need more of this humor

You might also here strongly-typed and loosely-typed instead of statically-typed and dynamically-typed.

What's the difference between JavaScript and Java? - Stack Overflow

java javascript
Rectangle 27 832

There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.

The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)

Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.

function Shape(x, y) {
    this.x= x;
    this.y= y;
}

We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:

Shape.prototype.toString= function() {
    return 'Shape at '+this.x+', '+this.y;
};

Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:

function subclassOf(base) {
    _subclassOf.prototype= base.prototype;
    return new _subclassOf();
}
function _subclassOf() {};

This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.prototype= subclassOf(Shape);

instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.

There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:

Function.prototype.subclass= function(base) {
    var c= Function.prototype.subclass.nonconstructor;
    c.prototype= base.prototype;
    this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};

...

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.subclass(Shape);

Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:

function Point() {
    Shape.apply(this, arguments);
}
Point.subclass(Shape);

So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:

function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!

Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:

...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw('Constructor called without "new"');
        ...

Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:

Circle= Shape.makeSubclass({
    _init: function(x, y, z) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    },
    ...
});

There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.

The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:

Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).

The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.

[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]

The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:

var ts= mycircle.toString;
alert(ts());

then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.

With the prototype way, you have to include a closure for every such assignment:

setTimeout(function() {
    mycircle.move(1, 1);
}, 1000);

or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():

setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);

if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.

There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:

function Shape(x, y) {
    var that= {};

    that.x= x;
    that.y= y;

    that.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };

    return that;
}

function Circle(x, y, r) {
    var that= Shape(x, y);

    that.r= r;

    var _baseToString= that.toString;
    that.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+r;
    };

    return that;
};

var mycircle= Circle(); // you can include `new` if you want but it won't do anything

Which way is proper? Both. Which is best? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.

But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.

Very nice gradual step-through from "class" def to object instantiation. And nice touch on bypassing new.

It seems like JavaScript is not your favorite language because you want to use it as if it had classes.

Of course I do, so does everyone: the class-and-instance model is the more natural one for a majority of the common problems programmers face today. I do agree that, on a theory basis, prototype-based inheritance can potentially offer a more flexible way of working, but JavaScript totally does not deliver on that promise. Its clunky constructor function system gives us the worst of both worlds, making class-like inheritance hard whilst providing none of the flexibility or simplicity prototypes could offer. In short, it's poo.

Bob I think this is an awesome answer - I've been grappling with these two patterns for a while and I think you've coded something more concisely than a Resig and explained with more insight than a Crockford. No higher praise can I think of....

It's always seemed to me that graphing classical inheritance paradigms onto prototypical languages like javascript is a square peg and a round hole. Are there times this is truly necessary or is this just a way for people to ham-fist the language to be the way they want rather than simply using the language for what it is?

How to "properly" create a custom object in JavaScript? - Stack Overfl...

javascript
Rectangle 27 828

There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.

The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)

Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.

function Shape(x, y) {
    this.x= x;
    this.y= y;
}

We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:

Shape.prototype.toString= function() {
    return 'Shape at '+this.x+', '+this.y;
};

Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:

Circle.prototype.toString= function() {
    return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}

This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.

So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:

function subclassOf(base) {
    _subclassOf.prototype= base.prototype;
    return new _subclassOf();
}
function _subclassOf() {};

This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.prototype= subclassOf(Shape);

instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.

There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:

Function.prototype.subclass= function(base) {
    var c= Function.prototype.subclass.nonconstructor;
    c.prototype= base.prototype;
    this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};

...

function Circle(x, y, r) {
    Shape.call(this, x, y);
    this.r= r;
}
Circle.subclass(Shape);

Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:

function Point() {
    Shape.apply(this, arguments);
}
Point.subclass(Shape);

So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:

function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
    this.x= x;
    this.y= y;
};

function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!

Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:

...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):

Function.prototype.makeSubclass= function() {
    function Class() {
        if (!(this instanceof Class))
            throw('Constructor called without "new"');
        ...

Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:

Circle= Shape.makeSubclass({
    _init: function(x, y, z) {
        Shape.prototype._init.call(this, x, y);
        this.r= r;
    },
    ...
});

There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.

The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:

Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).

The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.

[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]

The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:

var ts= mycircle.toString;
alert(ts());

then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.

With the prototype way, you have to include a closure for every such assignment:

setTimeout(function() {
    mycircle.move(1, 1);
}, 1000);

or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():

setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);

if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.

There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:

function Shape(x, y) {
    var that= {};

    that.x= x;
    that.y= y;

    that.toString= function() {
        return 'Shape at '+that.x+', '+that.y;
    };

    return that;
}

function Circle(x, y, r) {
    var that= Shape(x, y);

    that.r= r;

    var _baseToString= that.toString;
    that.toString= function() {
        return 'Circular '+_baseToString(that)+' with radius '+r;
    };

    return that;
};

var mycircle= Circle(); // you can include `new` if you want but it won't do anything

Which way is proper? Both. Which is best? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.

But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.

Very nice gradual step-through from "class" def to object instantiation. And nice touch on bypassing new.

It seems like JavaScript is not your favorite language because you want to use it as if it had classes.

Of course I do, so does everyone: the class-and-instance model is the more natural one for a majority of the common problems programmers face today. I do agree that, on a theory basis, prototype-based inheritance can potentially offer a more flexible way of working, but JavaScript totally does not deliver on that promise. Its clunky constructor function system gives us the worst of both worlds, making class-like inheritance hard whilst providing none of the flexibility or simplicity prototypes could offer. In short, it's poo.

Bob I think this is an awesome answer - I've been grappling with these two patterns for a while and I think you've coded something more concisely than a Resig and explained with more insight than a Crockford. No higher praise can I think of....

It's always seemed to me that graphing classical inheritance paradigms onto prototypical languages like javascript is a square peg and a round hole. Are there times this is truly necessary or is this just a way for people to ham-fist the language to be the way they want rather than simply using the language for what it is?

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to "properly" create a custom object in JavaScript? - Stack Overfl...

javascript
Rectangle 27 115

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

@changed what is the best compromise to have hidden functions (un-callable from outside), nice sintax (no .call) and small memory (no functions on the instance) ? Does that even exist ?

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 111

Simpler with Node.js

JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.

Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

var MyObject = (function () {

    // Constructor
    function MyObject (foo) {
        this._foo = foo;
    }

    function privateFun (prefix) {
        return prefix + this._foo;
    }

    MyObject.prototype.publicFun = function () {
        return privateFun.call(this, '>>');
    }

    return MyObject;
})();


var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined

The call function allows us to call the private function with the appropriate context (this).

If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:

function MyObject (foo) {
    this._foo = foo;
}

function privateFun (prefix) {
    return prefix + this._foo;
}

MyObject.prototype.publicFun = function () {
    return privateFun.call(this, '>>');
}

exports.MyObject = MyObject;
var MyObject = require('./MyObject').MyObject;

var myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
::
export default class MyObject {
  constructor (foo) {
    this._foo = foo;
  }

  publicFun () {
    return this::privateFun('>>');
  }
}

function privateFun (prefix) {
  return prefix + this._foo;
}
import MyObject from './MyObject';

let myObject = new MyObject('bar');
myObject.publicFun();      // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function

This is the best answer. The benefits of private methods, no junk.

.call

@janje ? What's the problem with .call ? btw you can move from ES5 and use the :: bind operator (think about using babel)

@janje Huh? That's the point of the question, there is no private f() in javascript (not at the moment).

@YvesM. The point of the question is choosing the best pattern that simulates it.

oop - JavaScript private methods - Stack Overflow

javascript oop private-methods
Rectangle 27 14

To understand why the solution with formHolder work you have to understand JavaScript prototypes chain first. Let's illustrate the first case without formHolder in the following pseudo code:

When the form directive is parsed it creates FormController which is set on the $scope property under key indicated in name attribute value. This is pretty much equivalent to:

$childScope.productForm = $formCtrl;

After which the 2 scopes look like this:

So you actually ended up with 2 properties on different scopes holding different objects. Now in the second case you have the following situation:

$parentScope = {
  //I'm a parent scope inside Ctrl2
  formHolder:{} //to avoid undefined reference error 
}

$childScope = {
  //I'm a child scope created by by ng-include 
  __protototype__: $parentScope 
}

When the form directive is setting FormController instance on the $scope this time it uses different property chain:

$childScope.formHolder.productForm = $formCtrl;
var formHolder = $childScope.formHolder; //since formHolder isn't defined on $childScope
//the JS runtime will look for it in the prototypes chain and find it inside $parentScope
//so here formHolder is the very same object you created and set on $parentScope
formHolder.productForm = $formCtrl;

Hope it helps to understand why the second option works. As for the second part of you question - your solution is simple and perfectly viable - but there are couple of other ways to handle it which is best depends on the actual usage context:

  • using directive without child scope to extract common markup and parts of functionality
  • using directive with child scope that would communicate state changes either via direct parent scope property access or via emitted events
  • using a custom include directive that would not create child scope

In angularJS it is call DOT notation by the way.

angularjs - Why form undefined inside ng-include when checking $pristi...

angularjs angularjs-ng-include
Rectangle 27 14

To understand why the solution with formHolder work you have to understand JavaScript prototypes chain first. Let's illustrate the first case without formHolder in the following pseudo code:

When the form directive is parsed it creates FormController which is set on the $scope property under key indicated in name attribute value. This is pretty much equivalent to:

$childScope.productForm = $formCtrl;

After which the 2 scopes look like this:

So you actually ended up with 2 properties on different scopes holding different objects. Now in the second case you have the following situation:

$parentScope = {
  //I'm a parent scope inside Ctrl2
  formHolder:{} //to avoid undefined reference error 
}

$childScope = {
  //I'm a child scope created by by ng-include 
  __protototype__: $parentScope 
}

When the form directive is setting FormController instance on the $scope this time it uses different property chain:

$childScope.formHolder.productForm = $formCtrl;
var formHolder = $childScope.formHolder; //since formHolder isn't defined on $childScope
//the JS runtime will look for it in the prototypes chain and find it inside $parentScope
//so here formHolder is the very same object you created and set on $parentScope
formHolder.productForm = $formCtrl;

Hope it helps to understand why the second option works. As for the second part of you question - your solution is simple and perfectly viable - but there are couple of other ways to handle it which is best depends on the actual usage context:

  • using directive without child scope to extract common markup and parts of functionality
  • using directive with child scope that would communicate state changes either via direct parent scope property access or via emitted events
  • using a custom include directive that would not create child scope

In angularJS it is call DOT notation by the way.

angularjs - Why form undefined inside ng-include when checking $pristi...

angularjs angularjs-ng-include