Will JavaScript ever become a 'proper' class based language? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm referring to MDN's article on JavaScript's 'future reserved words' (for use in the new strict mode) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Future_reserved_keywords . All the reserved words indicate that JavaScript will possibly follow a non-prototypical inheritance procedure, but what does this mean for already developed applications and modifications? Does anyone know how long these have been 'future reserved words', and whether or not these changes will come to light in the near future or not?
If this isn't the right place, feel free to move it.

Will JavaScript ever become a 'proper' class based language?
Fortunately, NO. It is already a proper language even without being class-based. You will never loose the power to create objects without classes.
I'm referring to MDN's article on JavaScript's 'future reserved words'. All the reserved words indicate that JavaScript will possibly follow a non-prototypical inheritance procedure
No, it's very unlikely that they will give this up. They just want to keep all options open to implement these functionalities, and want to prevent you using this syntax.
Like the Harmony drafts for classes and the current ES6 proposal show, most of these concepts can be implemented well in a prototypal world.
but what does this mean for already developed applications and modifications?
Not much. All changes in EcmaScript try to be as backwards-compatible as possible (remember what all this hassle with strict mode is about?).
Does anyone know how long these have been 'future reserved words', and whether or not these changes will come to light in the near future or not?
The article gives a good overview, I think. You may want to compare ES3, ES5 and the ES6 draft (maybe even earlier versions).
As said above, these are not intended to become "changes". Don't forget that back in the dark old days JavaScript syntax was based on Java, and did inherit its set of keywords. The removal of the Java types, and the addition of new keywords for more powerful concepts, can be seen as setting a direction in the development of EcmaScript.

All the reserved words indicate that JavaScript will possibly follow a non-prototypical inheritance procedure
Not at all. There is a difference between syntax and semantics. Only because you are creating classes with the class keyword in Java, doesn't mean that's what is happening in JavaScript as well. Under the hood, the languages behave differently.
ES6 introduces the class syntax:
class Person() {
constructor(name) {
this.name = name;
}
static create() { }
sayName() {
console.log(this.name);
}
}
Looks like a "class" right? But it's just syntactic sugar for constructor functions and their prototype object:
function Person() {
this.name = name;
}
Person.create = function() { };
Person.prototype.sayName = function() {
console.log(this.name);
};
The static keyword defines the function on the constructor function instead of the prototype (e.g. Person.create instead of Person.prototype.create).
Similarly I could imagine that final will define the property as not writeable and not configurable, at some point.
Bottom line: It's rather unlikely that the fundamental concepts of a language such as JS change completely.

In direct answer to the question, no; this would be a huge fundamental shift in the language.
Most of those have been reserved for ages. One of JavaScript's biggest flaws is NOT that it is a prototypal language, but rather that it in some ways tries to masquerade as a classic OOP language to make it feel more familiar to the old guard.
Neither class based nor is prototype based is inherently wrong or correct; but they are very different. Other prototypal languages have been around for along time, but they had not experienced as much popularity and subsequently familiarity to developers as class based languages.
A great comparative definition I have seen used for this is the following, courtesy of Eric Elliott.
Class based : OOP => Object ORIENTED Programming
Prototypal based : OOP => Object ONLY Programming
There is also a great video available from Eric on Prototypal inheritance here
http://ericleads.com/2013/06/classical-inheritance-is-obsolete-how-to-think-in-prototypal-oo/
And IMHO, one of the best reads over on Prototypal vs Classical inheritence; not even a technical read, but rather more philisophical.
http://carnotaurus.philipcarney.com/post/3010984357/classes-versus-prototypes-some-philosophical-and

Related

What is the motivation of arrow functions in Javascript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been working in Javascript. Lately they've added arrow functions in ES6 which have benefits as
Short Syntax
Scope safety of this
Clarity
However it has some disadvantage of using arrow function:
It doesn't inherit the Function prototype
We can't use it with callback function with dynamic context
Can't be used as constructor
I want to ask following things:
Why do they not inherit the Function prototype?
Are they made to increase the usage functional programming in javascript? (motivation behind them)
I asked this because mdn page says that it doesn't have a prototype but doesn't explain why it doesn't have a prototype.
I read this series by Eric Elliot and I think we're moving on functional programming approach in javascript and due to planned releases, is there any chance that we can remove OOPS in this in near future?
It doesn't inherit the Function prototype
Of course they do.
Object.getPrototypeOf(() => {}) === Function.prototype
We can't use it with callback function with dynamic context and it can't be used as constructor
Yes, that follows logically from the lexical this scope.
Are they made to increase the usage functional programming in javascript?
No, they're made to simplify writing functions, e.g. callbacks. Of course that makes them also useful for functional programming, but I don't think that's the primary motivation. The lexical this is an explicit OOP feature.
The statement on Function inheritance is false and was likely confused with the fact that they don't have prototype property. This is a direct consequence of the fact that they can't be constructors. A function that can't construct an object with new doesn't need prototype.
That's what they are, functions that don't have their own this context, they keep lexical this instead. They aren't just a shorter way to type function. Their potential use cases are all sorts of callbacks that need to keep the context or don't use this at all. If an arrow doesn't suit the case, that's the case for regular function then.
ES2015 arrows were borrowed from CoffeeScript where they have been proving their usefulness for a long time.

The difference between a class-based language (like Java or Python) and a prototype-based language (like Javascript)? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
prototype based vs. class based inheritance
This question came up at work the other day - what's the difference between a class-based language like Python, and a prototype-based language like Javascript? Aside from differing approches, both ways seem very similar and we struggled to find something that a class-based language could do that a prototype-based language couldn't, or vice-versa.
Can anybody elaborate or go into any detail on how they differ fundamentally?
I haven't found much online about the differences, just sites that show you how to accomplish one with the other (such as this: Simulating classes with prototypes in JavaScript)
Any enlightenment appreciated!
Check out this article. It is a detailed article discussing the differences between class-based and prototype-based languages.
Copy of the table summarizing the differences:
Class-based (Java)
Class and instance are distinct entities.
Define a class with a class definition; instantiate a class with constructor methods.
Create a single object with the new operator.
Construct an object hierarchy by using class definitions to define subclasses of existing classes.
Inherit properties by following the class chain.
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.
Prototype-based (JavaScript)
All objects are instances.
Define and create a set of objects with constructor functions.
Same.
Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the prototype chain.
Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
It seems like you're familiar with the actual languages, so you know what the difference is, right? I guess you're asking about the differences at a deeper, maybe more "philosophical", level.
Class-based languages tend to work from the top down, general to particular. The classic example would be where you define a 'Vehicle' class, and then subclasses like 'Car', 'Train'.
A prototype-based language would instead tend to start with the particular, in fact start with an instance of the particular and modify that.
I like this: http://steve-yegge.blogspot.ie/2008/10/universal-design-pattern.html
In the end it's not a question of if you can do inheritance in JS or whether there is something that you can do in one language but not the other. It's a deep difference in their ways of approaching problem solving. For a particular problem a good idiomatic solution that made best use of the language's features would probably be quite different in a prototype-based language from one in a class-based language.
The JavaScript guide of MDN has some good points, take a look: https://developer.mozilla.org/en/JavaScript/Guide/Details_of_the_Object_Model
Well, they're both (usually) Turning Complete. :)
Classes are about enforcing encapsulation, at the expense of some (or a lot of) run-time extensibility. Prototypes encourage encapsulation and allow almost unlimited run-time extension.
Seriously, prototype-based OO makes it very easy -- some would say dangerously easy -- to dynamically extend/derive from an object. Prototype languages therefore do not coexist easily with static typing. So if you like how compilers catch type errors, you will almost certainly be excluding prototype-based languages.
There's actually a very good discussion here: http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/ although there are others which are just as good I liked that one.

Is JavaScript 's “new” Keyword Considered Harmful (Part 2)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Reading through the following question, I feel the majority of the answers miss the point of why some people (Crockford) choose not to use the "new" keyword. It's not to prevent accidental calling of a function without the "new" keyword.
According to the following article by Crockford regarding prototypal inheritance, he implements an object creation technique that more clearly demonstrates the prototypal nature of JS. This technique is now even implemented in JS 1.8.5.
His argument against using new can be more clearly summed up as:
"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. JavaScript's constructor pattern did not appeal to the classical crowd. It also obscured JavaScript's true prototypal nature. As a result, there are very few programmers who know how to use the language effectively."
I don't necessarily consider "new" harmful, but I do agree that it does "obscure JavaScript's true prototypal nature," and therefore I do have to agree with Crockford on this point.
What is your opinion of using a "clearer" prototypal object creation technique, over using the "new" keyword?
You right, using new is considered harmful as it doesn't place enough emphasis on OO in JavaScript being prototypical. The main issue is that acts too much like classical classes and one should not think about class. One should think about Object's and creating new Objects with existing objects as blueprints.
new is a remnant of the days where JavaScript accepted a Java like syntax for gaining "popularity".
These days we do Prototypical OO with Object.create and use the ES5 shim.
There is no need for new anymore.
Before the days of ES5 being commonly implemented (only FF3.6 and IE8 are slacking) we used new because we had little choice. someFunction.prototype was the way to do prototypical inheritance.
I recently wrote up a "nice" demonstration of Object.create although I still need to iron out some kinks in the usage. The important thing is to separate Objects from factory functions.
I don't find that new obscures the prototypical nature of the language for me. Granted I've now spent some years getting to know the language well (having made the mistake originally of diving in and starting writing code without a clue how the language actually worked, to my initial cost).
I find new expressive in a way that prefixing "new" on function names or using a helper function, etc., isn't:
var fido = new Dog(); // Simple, clear
var rover = Dog(); // Very unclear (fortunately people mostly don't do this, but I've seen it)
var scruffles = newDog(); // Clearer, but hacky
var fifi = Object.create(Dog); // (Crockford) Verbose, awkward, not esp. clear
Whether it's prototypical or class-based (and most of that doesn't relate to the new keyword at all), I still think best in terms of functionality grouped together into building blocks (objects or classes or whatever) and then specific objects I can muck about without affecting those building blocks. For me, new as a means of clearly identifying my intent is neither classy or prototypical, it's just clear.
For me, new is just as vital a part of JavaScript as prototypes themselves are, as the wonderfully dexterous functions are. The is is no conflict.
And speaking practically, there are a lot more programmers out there used to using new to create new instances of things than not, and it's a widespread practice in the JavaScript community despite Crockford's efforts (don't misunderstand, I have a lot of respect for Crockford). If I'm staffing up a project, I don't want the retraining hassles.
This is not to say that the way that you define hierarchies of prototypical objects in JavaScript is a thing of beauty and a joy forever. It's a royal pain, especially without the ECMAScript5 enhancements. But define a helper function to help you wire up your hierarchies (whatever you want to call them), and you're done. (See update below.)
[And yes, the whole thing about constructor functions being called without new really is a red herring (you did say you didn't think it was a main point either). You almost never see it happen in the real world. Actually, some of what JavaScript does with that is quite nice (the way String and Number cast, for instance); other parts (what Date does **shudder**) are not so nice...]
As of ES2015 (ES6), creating hierarchies of prototypes and constructors is a breeze, thanks to the new class syntax. No need for helpers anymore.
class Base {
constructor(name) {
this.name = name;
}
greeting() {
return "Hi, I'm " + this.name;
}
}
class Derived extends Base {
constructor(name, age) {
super(name);
this.age = age;
}
greeting() {
return super.greeting() + " and I'm " + this.age + " years old";
}
}
That doesn't mean we want them for everything, of course. I use Object.create to great effect when I need to extend a single object.
My biggest problem with new is that it violates the Open/Closed principle. Because of the way that new manipulates the value of this, constructors are closed for extension, which means if you need to extend it, you must modify it, possibly breaking callers in the process.
Some examples of how factories can be extended that new doesn't allow:
Hide the details of object creation. (The rest of these are examples of why you might want to do that)
Store mutable prototypes and init functions on the factory object, accessible with this. (With new, this always refers to the newly created object).
Extend the pool of possible object types by allowing you to add capabilities to the factory object (extensible polymorphism).
Redefine the meaning of this during instantiation with .call() or .apply() (extending code-reuse).
Return a proxy to a new object in another memory space (iframe, window, different machine).
Conditionally return a reference to an existing object (Actually, you can do that with new and constructors, but then this is meaningless and misleading inside the constructor because a new instance gets allocated and then thrown away if you return something other than a new object).
Enable changes to instantiation strategy without breaking callers.
Note: I'm constantly irritated that I can't easily use any of these strategies with Backbone.js because it forces you to use new, unless you wrap it, but then you close off its standard inheritance mechanism. By way of contrast, I have never found myself irritated that jQuery uses a factory function to instantiate jQuery-wrapped DOM collections.

Why to use class based OOP style inheritance in javascript?

If I'm not completely wrong every framework/library/approach in javascript tends today to mimick class based OOP style inheritance. Reasons for this seem to be people thinking class based OOP inheritance is far easier to understand and that most programmers know OOP.
In my experience I don't find evidence for either of this opinions. I think javascript prototypal inheritance is just fine (and I doubt the usefulness to force another paradigm upon a language than the one it is built on). Most of the developers I meet aren't even that good in classical OOP either. So what are the reasons to choose classical OOP style inheritance over prototypal inheritance?
I think the answer is in your question - most programmers are far more familiar with class-based OOP than prototype-based.
In fact I'd go so far as to say the majority don't believe you can have objects without classes.
note that even if you're arguing for prototype-based OOP, you call it 'prototypal', and class-based OOP just 'OOP'. so, you yourself suffer from this bias, thinking OOP=>classes, prototypes => something else.
and since most people think that OOP is the right way no matter the problem, then prototypes must be inferior.
so, to answer your question, it's two factors:
a bad definition: "OOP => classes"
propaganda: "it must be OOP, or you're not worthy"
since you're still bounded by the first, you try to explain that prototypes are an exception of the second. much easier is to correct them:
there are many ways to do objects, classes are just the easiest one for static languages. most people are taught to program with static languages, and most of them try to use any language just like the first one they learned.
there are many ways to structure a programming solution, OOP are great at some and lousy at others.
I feel as if you already know the answer to your question because you stated a part of it when you said
Reasons for this seem to be people
thinking class based OOP inheritance
is far easier to understand and that
most programmers know OOP.
Neither paradigm is more right than the other for tackling a problem. I believe the main reason is that everyone is taught OOP through Java these days. So when people encounter OOP they think "oh classes" because it's what they are familiar with. And whenever they want to solve a problem they will most likely use what they know.
I would also state that it does no benefit for the programmer to use a paradigm he is unfamiliar with. Most of us must use javascript for client side web development and use a class based OOP language on the server. I personally would not want that OOP impedance mismatch whenever I had to look at the javascript side of an application.
At a certain level the fact that everyone is trying to implement class based OOP in javascript is an educational issue. At another level it's a psychological one.
For a long time I considered prototype-based OOP as weak, bad and wrong version of class-based OOP. Then, after a critical amount of information leaked into my head, I now understand OOP in more abstract way, and find both ways acceptable in general.
So what are the reasons to choose classical OOP style inheritance over prototypal inheritance?
Actually, I believe that some frameworks are "sort of" combining approaches. Take for example the Parasitic Combination Inheritance pattern. This is what YAHOO.lang.extend is doing.
It uses prototypal inheritance and a helper function to inherit prototypes and constructor stealing. Wow, that sounds complex...well yes it is - here's my implementation and test for example:
// Prototypal Inheritance
Object.prototype.inherit = function(p) {
NewObj = function(){};
NewObj.prototype = p;
return new NewObj();
};
// Paraphrasing of Nicholas Zakas's Prototype Inheritance helper
function inheritPrototype(subType, superType) {
var prototype = Object.inherit(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
};
function SubType(name, age) {
Parent.call(this, name);
this.age = age;
};
inheritPrototype(SubType, Parent);
SubType.prototype.getAge = function() {
return this.age;
};
I have a test for this code:
describe 'Parisitic Combination Inheritance'
it 'should use inheritPrototype (to call parent constructor once) and still work as expected'
sub = new SubType("Nicholas Zakas", 29)
sub.toString().should.match /.*Nicholas Zakas/
sub.getAge().should.eql 29
charlie = new SubType("Charlie Brown", 69)
charlie.arr.should.eql([1,2,3])
charlie.arr.push(999)
charlie.arr.should.eql([1,2,3,999])
sub.arr.should.eql([1,2,3])
sub.should.be_an_instance_of SubType
charlie.should.be_an_instance_of SubType
(sub instanceof SubType).should.eql true
(sub instanceof Parent).should.eql true
end
end
And of course, if you're paying attention to my literals you see: Nicholas Zakas, the guy I got this from ;) The big wins for this one: instanceof works (big deal some say and I kind of agree); instances don't share state on reference types like arrays (a biggie!); parent constructor only called once (a biggie!).
BTW, I have examples of most of the popular inheritance patterns here: My TDD JS Examples
I'd argue that the language itself steers people into the classical mindset with it's choice of "new" as a keyword, and by introducing concepts like "constructors" in the language specification. In a way this is limiting - imagine the change in mindset if instead we had a clone keyword, and the concept of traits ala SELF.
When I was writing my first scripts, it was cool and handy to have such a simple language.
But today you do not just want to toggle a buttoncolor, you want to build complex applications in JavaScript. Others might like to use your popular application and would love to see s community providing plugins.
Now, this is much easier to realize with OOP - especially because a lot of programmers a familiar with OOP concepts.
One reason may be that your server side is likely to be OO (ASP.NET, Java, etc.), so it's just easier to think in the same paradigm on the client. Not necessarily better, but easier.

Object Oriented Javascript best practices? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm finding myself coding a big project in Javascript. I remember the last one was quite an adventure because hacky JS can quickly becomes unreadable and I want this code to be clean.
Well, I'm using objects to construct a lib, but there are several ways to define things in JS, implying important consequences in the scope, the memory management, the name space, etc. E.G :
using var or not;
defining things in the file, or in a (function(){...})(), jquery style;
using this, or not;
using function myname() or myname = function();
defining methods in the body of the object or using "prototype";
etc.
So what are really the best practices when coding in OO in JS ?
Academic explanations really expected here. Link to books warmly welcome, as long as they deal with quality and robustness.
EDIT :
Got some readings, but I'm still very interested in answers to the questions above and any best practices.
Using `var` or not
You should introduce any variable with the var statement, otherwise it gets to the global scope.
It's worth mentioning that in strict mode ("use strict";) undeclared variable assignments throws ReferenceError.
At present JavaScript does not have a block scope. The Crockford school teaches you to put var statements at the beginning of the function body, while Dojo's Style Guide reads that all variables should be declared in the smallest scope possible. (The let statement and definition introduced in JavaScript 1.7 is not part of the ECMAScript standard.)
It is good practice to bind regularly-used objects' properties to local variables as it is faster than looking up the whole scope chain. (See Optimizing JavaScript for extreme performance and low memory consumption.)
Defining things in the file, or in a `(function(){...})()`
If you don't need to reach your objects outside your code, you can wrap your whole code in a function expression—-it's called the module pattern. It has performance advantages, and also allows your code to be minified and obscured at a high level. You can also ensure it won't pollute the global namespace. Wrapping Functions in JavaScript also allows you to add aspect-oriented behaviour. Ben Cherry has an in-depth article on module pattern.
Using `this` or not
If you use pseudo-classical inheritance in JavaScript, you can hardly avoid using this. It's a matter of taste which inheritance pattern you use. For other cases, check Peter Michaux's article on JavaScript Widgets Without "this".
Using `function myname()` or `myname = function();`
function myname() is a function declaration and myname = function(); is a function expression assigned to variable myname. The latter form indicates that functions are first-class objects, and you can do anything with them, as with a variable. The only difference between them is that all function declarations are hoisted to the top of the scope, which may matter in certain cases. Otherwise they are equal. function foo() is a shorthand form. Further details on hoisting can be found in the JavaScript Scoping and Hoisting article.
Defining methods in the body of the object or using "prototype"
It's up to you. JavaScript has four object-creation patterns: pseudo-classical, prototypical, functional, and parts (Crockford, 2008). Each has its pros and cons, see Crockford in his video talks or get his book The Good Parts as Anon already suggested.
Frameworks
I suggest you pick up some JavaScript frameworks, study their conventions and style, and find those practices and patterns that best fit you. For instance, the Dojo Toolkit provides a robust framework to write object-oriented JavaScript code which even supports multiple inheritance.
Patterns
Lastly, there is a blog dedicated to explore common JavaScript patterns and anti-patterns. Also check out the question Are there any coding standards for JavaScript? in Stack Overflow.
I am going to write down some stuffs that I read or put in application since I asked this question. So people reading it won't get frustrated, as most of the answers are RTMF's in disguise (even if I must admit, suggested books ARE good).
Var usage
Any variable is supposed to be already declared at the higher scope in JS. So when ever you want a new variable, declare it to avoid bad surprises like manipulating a global var without noticing it. Therefore, always use the var keyword.
In an object make, var the variable private. If you want to just declare a public variable, use this.my_var = my_value to do so.
Declaring methods
In JS, they are numerous way of declaring methods. For an OO programmer, the most natural and yet efficient way is to use the following syntax:
Inside the object body
this.methodName = function(param) {
/* bla */
};
There is a drawback: inner functions won't be able to access "this" because of the funny JS scope. Douglas Crockford recommends to bypass this limitation using a conventional local variable named "that". So it becomes
function MyObject() {
var that = this;
this.myMethod = function() {
jQuery.doSomethingCrazy(that.callbackMethod);
};
};
Do not rely on automatic end of line
JS tries to automatically add ; at the end of the line if you forget it. Don't rely on this behavior, as you'll get errors that are a mess to debug.
First ought to read about the prototype-based programming so you know what kind of beast you're dealing with and then take a look at JavaScript style guide at MDC and JavaScript page at MDC. I also find best to force the code quality with a tool, ie. JavaScript Lint or other variants.
Best practices with OO sounds more like you want to find patterns than concentrate on code quality, so look at Google search: javascript patterns and jQuery patterns.
Speed up your JavaScript
You might want to check out Secrets of the JavaScript Ninja by John Resig (jQuery). "This book is intended to take an intermediate JavaScript developer and give him the knowledge he needs to create a cross-browser JavaScript library, from the ground, up."
The draft is available through the publisher:
http://www.manning.com/resig/
Douglas Crockford also has some nice JavaScript articles on his homepage:
http://www.crockford.com/
I often feel like the only guy here who uses MooTools for my javascript.
It stands for My Object Oriented Tools, mootools.
I really like their take on OOP in javascript. You can use their class implementation along with jquery too, so you don't have to ditch jquery (though mootools does it all just as well).
Anyway, give the first link a good read and see what you think, the second link is to the mootools docs.
MooTools & Inheritance
MooTools Classes
Here's a book that covers most of the bases:
Object Oriented Javascript for high quality applicatons and libraries

Categories