Why was JavaScript implemented using prototypal inheritance? - javascript

There are lots of articles and posts explaining how JavaScript inheritance works, but why was JavaScript implemented using prototypal inheritance instead of classical inheritance?
I love JavaScript, so I'm not saying it's bad thing... I'm just curious.

Here's what Brendan Eich has to say about what happened:
https://brendaneich.com/2008/04/popularity/
As I've often said, and as others at Netscape can confirm, I was recruited to Netscape with the promise of "doing Scheme" in the browser. At least client engineering management including Tom Paquin, Michael Toy, and Rick Schell, along with some guy named Marc Andreessen, were convinced that Netscape should embed a programming language, in source form, in HTML.
The diktat from upper engineering management was that the language must "look like Java". That ruled out Perl, Python, and Tcl, along with Scheme.
I'm not proud, but I'm happy that I chose Scheme-ish first-class functions and Self-ish (albeit singular) prototypes as the main ingredients. The Java influences, especially y2k Date bugs but also the primitive vs. object distinction (e.g., string vs. String), were unfortunate.

JavaScript was originally supposed to be very much like Lisp. Even after the syntax was changed to more closely resemble C/Java, it is still Lisp in C's clothing. I think the answer lies in it's functional programming origins. In pure FP, there is no mutable state, which means no mutable objects. If you relax the rules a bit and get slightly creative, you end up with something like protypal inheritance, i.e., you can extend objects but not modify the original object. It provides the same power as inheritance and still gives you some immutability.
Finally, twist the language around to make it look like C++ and Java, and viola, you have new someFunction() and the rest is history.

Because it was heavily influenced by Self. Both Wikipedia and the ECMA-spec mention this.

I think it was chosen because it is easy to implement, needs no extra keywords and users don't need to understand it to be able to use the language. It is also more powerfull and flexible than class based inheritance.
It's a natural choice for a untyped language. The main advantages of class based inheritance are that it allows static typing and thus type checking and a faster table based lookup implementation.

Prototypical inheritance (with closures) allows others to do things that were never envisioned. It's the meshing of several paradigms that have come together to achieve general purpose programming.
With a prototype language, you can have "mix-ins" for your classes. You can accomplish the level of encapsulation you desire, without language specific keywords. In short, prototype languages are awesome.
I hate to say it, but JavaScript, plus some libraries, can do everything I need it to. It was subversive in its development (supposed to be subservient to Java). It has much power, in the simplest of implementations.
With enough study / playing around, you'll begin to see the advantages of it's inspiration. JavaScript is one of the few languages that "hid" it's potential intentionally. You gotta get into the politics if you want to know the "why." But, it's for this reason, that it's awesome.

Related

class use in a prototypal inheritance-based language

The following answer to this question does a great job explaining the differences between classical inheritance and prototypal inheritance. this was of interest to me to understand because I started working in Java, but moved over to Javascript.
In his answer, he states for prototypal inheritance that, "All of the business about classes goes away. If you want an object, you just write an object."
Yet there is so much documentation and questions on how to "write classes" in Javascript.
Why is there push to make the language something it is not. I'm looking for concrete examples of cases where using classes in JS applications are more sensible in this prototypal language and the benefits of awkwardly fitting a square peg into a round hole. As Aravind put it, why are people learning Javascript by comparing it to others, and not as it was intended... and why is this practice seemingly encouraged?
Bottomline question: Why are classes being introduced in ECMAScript 6?
The masses like classes.
There's nothing "more" or "less" natural about prototypal inheritance, this is entirely subjective. JS is its own language, just like Smalltalk and Self had different ideas about what it meant to be an object.
ES6 classes are syntactic sugar. They normalize/clean up how inheritance/etc are to be used in JS.
Similar to CoffeeScript, they attempt to standardize how OOP is done in JS, and make it more familiar to people that aren't used to prototypal inheritance.
Why are people learning Javascript by comparing it to others, and not
as it was intended?
This gets into cognitive and learning theory, but the short version is that humans like things that are familiar, and one of the ways we learn is by relating new ideas to knowledge we already have.
Why are classes being introduced in ECMAScript 6?
Classes were almost introduced in ECMAScript 4, actually. I think there are good arguments for OOP being a useful pattern for writing complex software, and class based inheritance is more familiar to many programmers than is prototype based inheritance. I think an equally valid question might be "why does JavaScript still implement prototype based inheritance when most people who learn it will be more comfortable with class based inheritance?"
If you're curious what classes in JavaSCript might look like, take a look at ActionScript 3, which is based on that draft of EMCAScript 4 with class based inheritance.
Of course, just because ECMAScript adds class support does not mean that JavaScript will, or at least that it will any time soon.
I found this article by Zakas explaining it clearly, that it's just syntactic sugar, and at the end of the day Javascript will work the same way.
Don't worry about having to learn classes or having to shift your programming styles, nothing changes. :)
Why are classes being introduced in ES6? Sugar, of the syntactic variety.
Classes are very good for people who come to JavaScript from object-oriented languages (like Java).
This is the experience I've made several times already. I had a number of J2EE web projects with good Java dev teams, who had some JavaScript knowledge, but not much. Almost the first thing I did was to explain prototypes, prototypal inheritance and how one can implement the OOP paradigm using prototypes - basically the pseudoclassical inheritance. (Now I routinely do a "JavaScript for Java Developers" workshop almost in every project of that kind.)
With that approach I mostly saw good code coming out. Most Java developers tend to stick to the pseudoclassical pattern and are quite happy with it. This is most probably not what JS ninjas out there would write, but, frankly, I don't care. The code is easy to understand and to maintain, people had a good learning curve and were productive very fast.
Prototype languages, like JavaScript, are really great for small scale, short term projects that don't require a lot of testing or maintenance. Their simple and flexible functionality really shines in this realm.
Class based languages on the other hand tend to be a little more rigid and require more setup, which isn't as great at the little stuff but the extra structure is helpful to keep the larger, long term projects scalable and manageable.
When JavaScript first started, its primary function was to manipulate static DOM elements, which is a great application for a prototype language. Fast, flexible and simple -- no fuss. Now, however, the role that JavaScript fills is much more complex and is more and more an application than a simple script. Adding classes to a prototype language does sound a little funny, but the added structure classes provide, along with their widespread familiarity could very easily help teams of developers handle the complexity of modern JavaScript applications.

What type of language is JavaScript

I'm in a beginning HTML class and our textbook says that JavaScript is an object-based scripting language. On our quiz, one of the questions was "JavaScript is an object-oriented scripting language, True or False." I put False because it's my understanding that object-based and object-oriented are two different things. I got the answer wrong.
Is JavaScript indeed an object-oriented language?
Thanks for any clarification you can give!
JavaScript uses prototype-based programming, which is a type of object oriented programming. Prototypes are a way of reusing behaviors by cloning existing objects instead of doing class based inheritance. It's different enough from the standard class based object oriented programming that few people bother to learn it well enough to make good use of it.
http://en.wikipedia.org/wiki/Prototype-based_programming is a useful reference.
The definition of Object Oriented is sometimes subjective. For some, any language that deals with "Objects", is Object Oriented. For others, the entire language and its construct must utilize objects to be counted as Object Oriented (think SmallTalk or Java).
In javascript, you're able to write a script that has no objects in it or you can create heavily object oriented code. Whether or not you call it Object Oriented is really dependant on what school of thought you follow.
I'd say that object-oriented is not a feature of programming languages, it is a feature of code. Code does not grow object-oriented, prototype-based or functional simply because it is written in a specific language, it obtains such a quality only if the author use that style.
Sure, it makes sense to call a language like Java object-oriented since the language is designed specifically for that paradigm, but JavaScript works well with a load of different paradigms, so you really can't put a sticker on it.
This answer I am sure has been answered elsewhere.... object-based and object-orientated are the same thing, used interchangeably. There is actually no difference in the terminology - some prefer one over the other.
To answer your question, yes, Javascript is object-orientated or object-based.
Javascript is a superset of ECMAScript, which is a multi-paradigm ( functional, procedural ), prototype-based, functional, imperative scripting language with duck/weak/dynamic typing and is influenced by Perl, C, Python, Java, Scheme.
ECMAScript was created by Brendan Eich. Source: http://en.wikipedia.org/wiki/ECMAScript
It adopts C constructs such as if and else and for, but also has closures and lambdas from Scheme, as well as prototype-based inheritance from Self so it can be used in an OO way.
Object-based, object-oriented, basically the same thing. It's my impression that object-oriented is a bit stricter than object-based.
Object-based implies that the language uses the idea of encapsulating state and operations inside "objects".
Object-oriented means that the language is designed for programming with objects.
The difference is pretty minor. See the wikipedia articles on object-based language and object-oriented programming to get a finer idea of the difference.
The term Object-oriented programming (OOP) is not very well-defined in general. See Jonathan Rees note on OO: Rees on OO. Javascript has an OO model based on a concept named prototypes. The prototype-based model is different from the model used in Java or C++, but it certainly falls underneath the general umbrella that is OOP-based languages.
Perhaps the term "object-based" was used to underline this fact about javascript. It uses objects, but not in the same vein as Java or C++ (or C#) does.
The object-oriented fundamentals are there but are structured differently from other more common object-oriented languages like C# and Java. You can create object constructors and methods, and access and retrieve object properties. JavaScript was designed to be a completely
object-oriented language from the start but somehow was influenced by Perl and Python and therefore the current programmatic idioms.
What is wrong with this object-oriented notation in javascript?
function Class( name, teacher ) {
this.name = name;
this.teacher = teacher;
}
If your quiz defined neither ‘object-oriented’ nor ‘scripting language’, I can’t possibly see how you can be expected to answer the question.

What can JavaScript learn from Ruby?

The ECMAScript working group has started working on the next edition of the language. What can they learn from Ruby?
This is actually a much more challenging question than it appears at first.
The main reason for this is that it's been shown to be very difficult to force browser vendors, by way of specification, to implement the pet or favourite features of language enthusiasts, users, other vendors, or academics without very good justifications. This is how we ended up with the ES4 spec pretty much dead on the table, which yielded a much less ambitious (though still pretty awesome) ES Harmony. A language like JavaScript which has such insanely tricky political deployment and implementation issues is simply unable to be the type of awesome experimental playground that Ruby has been for much of its lifetime. Anyone who has followed es-discuss (the ECMAScript language development mailing list) has probably noticed by now that it takes many many months of debate and experimentation to merely articulate and agree upon common language features like, in recent memory, operator overloading, or short form lambda notation.
Perhaps it may be too much to ask of any working group to nail a spec that will target every device on the planet? On the surface it would appear that it's a very narrow band of lessons, even the social ones, that can be easily transferred from Ruby to the JavaScript.
To that end, and to ease the burden of Brendan Eich and his group:
One of the most urgently useful "lessons" to bring to the language from a perspective inspired by Ruby (or LISP) would be language malleability. The ability to introduce new features, syntax hacks and domain-specific languages not originating from a inner cabal of spec writers would be incredibly valuable. Allow the language to be a good place for modular extensions to the language to be made, and for those extensions to be self-hosted, so as to minimize fragmentation risks and to allow those changes to permeate and be mashed up, etc.
Such malleability would allow the community at large to apply lessons from all sorts of directions and allow the Internet to decide over time which lessons are worthwhile from which language, etc. We've already got a high rate of iteration and evolution happening at the other ends of this sandwich, i.e. in browsers themselves (eg: HTML5), and in js libraries. If that was able to happen more intimately at the language level, we could see some very interesting things happen very quickly.
[addendum/edit]:
The language has to be able to morph significantly because a small group of people is simply incapable of anticipating all the things it'll ever be used for. A theme that comes up on es-discuss often is that underlying current of designing "a language for the next 10-15 years". IMHO, this is an incredibly unrealistic goal. If you don't build it, the system will evolve an alternative long before spec's intended lifetime. With the immense speedup in javascript engine/JIT technology of late, we're already seeing the early signs of this happening in the form of new languages being written on top of JavaScript or being cross-compiled on the fly into JavaScript. Yep, even Ruby: http://hotruby.yukoba.jp/
Embrace function programming, don't try to bury it in static language constructs
Having a name that sounds like a gemstone is much better than a name that sounds like a skin disease.
But don't name your new language after today's hottest thing (that's how we all got into this "Java"script mess in the first place....)
build a standard library around the heavy use of closures, both for collection iteration and for the acquire resource/yield resource/dispose of resource pattern. that's one of ruby's biggest wins, imo. of course, part of what enables this is the brilliant decision to give every method one 'free' closure parameter, with syntactic support, so it's probably not going to look as nice in javascript. the techniques are still useful, though.
I can't see to much that it could learn from Ruby. The standards group has already given the language a mean to do resend messages, or messages to the protoype. The method_missing functionality might be cool to implement, but it isn't as necessary as better refelction facilities.

Javascript book which teaches javascript the language, not dom

I am a pretty good programmer(IMO only, of course. Know Python, Java well. Tried my hands at Lisp, Ruby, Haskell). I also know how to use Jquery reasonable well, so I know Dom manipulation.
I want a recommendation on a Javascript book, which teaches the Language. My criteria are,
1. Fast paced and for programmers who know programming. Dont tell me what loops are.
2. Teaches the language not the Dom manipulation.
3. Preferable ebook. Non free is fine.
JavaScript: The Good Parts.
Like others I'd firstly recommend JavaScript the good parts. Another option to consider is JavaScript the definitive guide by David Flanagan. This is also a good book that covers the language well- certainly enough depth for a programmer interested in particular features of javascript. The language part is seperate from the client side stuff- so you can just read the bits that interest you.
Update- I've just checked the book on Amazon it has a whopping 286 customer reviews!
Another good one is "Pro Javascript Design Patterns" by Harmes & Diaz. It starts by showing a number of approaches for simulating classes, classical inheritance, private members, etc., then builds on that to implement several of the more common design patterns seen in other OO languages. Some of the examples do involve the DOM, but they really give a feel for the flexibility of the core language.
There are a few excellent JavaScript books for various levels.

Javascript as a functional language

I am looking get to grips with functional programming concepts.
I've used Javascript for many years for client side scripting in web applications and apart from using prototypes it was all simple DOM manipulation, input validation etc.
Of late, I have often read that Javascript is one of the languages that supports functional programming.
With my familiarity and experience with Javascript, my preference is to use it to learn functional programming. I expect I would be able to concentrate more on the main functional concepts and not get bogged down or distracted by a completely new syntax.
So in summary, is Javascript a good choice to learn functional programming concepts? What capabilities in Javascript are relevant/support functional programming?
JavaScript supports first class functions. See Use functional programming techniques to write elegant JavaScript.
Higher Order Javascript is a great way to get familiar with the functional aspects of javascript. It's also a relatively short read in case you want to get your feet wet without diving into a larger book.
I would say that although you can quickly grasp some functional programming concepts with JavaScript, using JavaScript consistently like a functional programming language is not a common practice. At least not obviously common. Most people don't post tutorials that pinpoint how to do functional programming with JavaScript -- the one marxidad pointed out is actually a pretty decent example, but you won't find a lot of that. The functional aspects are not often apparent, just like when people use closures in JavaScript, but are unaware that they are doing it.
The idea that you would pass two functions through as arguments to a third function, and then have the return value be some execution related to the first two functions is an advanced technique that almost always appears only in the core of full-blown libraries like jQuery. Self executing anonymous functions and the like have gained ground, but are still not used consistently. The majority of tutorials often focus instead on JavaScript's OO capabilities, like how to create properties and methods, scope, access control and also how to use the prototype property of constructors. Honestly, if functional programming is what you want, then I would choose a language known strictly for this capability.
I don't remember who said it, but javascript has been called "Scheme with Algol syntax". So for learning Scheme/Lisp, Javascript isn't a bad start. Note though that functional languages like Lisp are quite different from pure functional languages, such as Haskell.
Apart from "first-class functions" (Meaning that functions are values, that can be assigned to variables), lexical scope is also an inherent part of what makes a functional language.
Higher Order Javascript and The Little Javascripter has been mentioned already. They are both excellent texts. In addition, Higher Order Programming in Javascript may be an easier start.
Although javascript supports FP to some degree, it does not directly encourage it. That's why projects like Oliver Steele's Functional exist, to fill in the gaps. So I wouldn't recommend it for learning FP. Check out F# instead.
I would recommend reading The Little Schemer, which is a fairly slim book about recursion and is a good introduction to the functional style. Whilst it's focused on Scheme it can easily be applied to JavaScript, see http://javascript.crockford.com/little.html. I found it really helpful in my javascript development, although it gets quite tricky towards the end.
Javascript is a multi-paradigm language. If your goal is to learn functional language concepts, try starting with a pure functional language like OCaml or Haskell.
Also, Eloquent JavaScript: Functional Programming chapter.

Categories