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.
Related
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
Every time I see JS namespacing referenced it is implemented with an object expression. If I want to be sure that my namespace exists before it is assigned any properties, can I instantiate it by way of function declaration?
e.g.;
function namespace() {}
vs
let namespace = {};
The former being hoisted, and guaranteeing that properties I append to my namespace won't encounter an "undefined" error.
I know it works at least for my basic tests, but are there pros/cons to this?
Edit: Another example: https://jsbin.com/nuquxuxinu/edit?js,console
Edit: Bergi provided some good clarification, but I still need to be convinced as to why using a function as a namespace is a bad idea.
ANSWER: Since my question was marked as "opinion based" I can only deduce that there is no technical reason why you shouldn't use a function for a namespace.
No, you should not make your namespace object a function object unless you need it to be callable. If the function does nothing (like in your example), don't use a function.
Hoisting does not have any benefits for you. The variable declaration let namespace is hoisted just as well. What is actually important is that the members of your namespace are created before you use them, and they are created by assignment. Just put them in the right order in your file - first the namespace object instantiation, then the properties of that object (if they were not already created as part of it in an object literal), last the code that uses the namespace.
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
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
When we define a top level named function in Javascript, it becomes a method of the window object. What is the reason for this design decision?
Javascript always run in a particular global context.
In a browser environment that is the window object, so when you define a global, you're actually adding it to window...
Here is another excellent stackoverflow answer explaining why this is so:
Is window really global in Javascript?
What is the reason for this design decision?
I can't answer that, we'd have to ask the guy who designed the language, and the committee that maintains its specification. But maybe this will give you some insights: internally, variables (local or global) are always stored in "Lexical Environment" objects. So, they are always properties, and they even have their own properties (to mark them as read-only, non-deletable, etc.).
The environment objects are not exposed in browser JavaScript, except for the global object (as pointed out by squint in the comments, ECMAScript doesn't actually require that the global variable object be exposed, that's up to the implementation.)
It happens that it was decided that the global object is the same as the window object in browsers. Why? Again, I can't answer that. They just decided not to use a dedicated global (or whatever) identifier.
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
What is better practice for creating functions?
For example if I want to shuffle an array, is it a better application to just create a regular function or prototype function? Are there drawbacks/advantanges of using one over the other?
function shuffleArray(array) {
...
}
or:
Array.prototype.shuffle = function() {
..
}
Generally, extending built–in prototypes is disliked because it can break for..in loops and may clash with future language extensions, noting that implementations can (and are encouraged to) extend the language independently of ECMA-262.
I doubt that the difference in performance is significant. It's more common to add the shuffle functionality to some object that needs shuffling than to the built–in Array prototype, though the generic code to shuffle something might be in a stand alone function and be re–used.
If you are going to add shuffling to an object, then prototype inheritance is a good choice as it is easily recognised and understood so maintenance should be easy. Also, it makes efficient use of memory and processing (though for a small number of functions the difference is trivial).
Using prototype is better for object oriented design because it cannot be done on the fly. Also when using this notation obj.member it will check the non prototype version first. Prototypes allow for simulated inheritance, imo javascript is kinda just a bad language but I would say if you are trying to use good object oriented design it is better to use prototypes. Another thing you can do with prototypes is a.__proto__ which will reference the original prototype of the object even if it has been modified
Just make a regular function in this case. Not only is it simple, (and probably faster), but most importantly, it avoids messing with the global Array.prototype namespace.
The only really big advantage for prototype functions is when you need to do object orientation. Using the prototype method lets all instances share the same function while using closures will need to create a new coy of the function for each instance.
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.