I have a function in the prototype of the constructor:
function Animal(name) {
this.name = name
}
Animal.prototype.generateToys = function(numberOfToys) {
if(numberOfToys == 1) {
this.createToys();
}
else {
this.createToys();
}
}
The createToys still needs to be declared. And that´s where my question is pointing towards. Assuming that generateToys will be the only method that will call createToys(), would it be better to create createToys inside the method generateToys like so:
function Animal(name) {
this.name = name
}
Animal.prototype.generateToys = function(numberOfToys) {
if(numberOfToys == 1) {
this.createToys();
}
else {
this.createToys();
}
function createToys() {
...
...
...
}
}
Or would you create it as a method(prototype) like the following:
Animal.prototype.createToys = function() {
...
...
...
}
What would be better and why? :)
If you put it inside the generateToys() method, it will be re-declared every single time you call that method, and then be removed from scope when the method completes. Most of the time this isn't what you want, so you'd prefer to create it as a separate method.
That depends on your architecture.
If you plan to have many instances of Animal then adding your method to the prototype is better, otherwise you will be creating a lot of private functions and that is costly (in terms of performance).
declaring the function inside the prototype limits the visibility outside that scope and cause the function to be declared everytime you call Animal.prototype.generateToys() (waste of memory)
Animal.prototype.generateToys = function(numberOfToys) {
var createToys = function createToys() {
}
})
declaring it on the prototype means that each of your instance can call it directly and you will have only one spot in memory with that declaration because the prototype itself it's a single reference shared by all your instances.
Related
Is there any disadvantage to make all the instance methods an arrow function? This way, we don't have the "lost binding" issue.
So for example, the following has the lost binding issue. We don't usually write code to invoke this.foo() this way, but in ReactJS, for example, we use onClick={this.foo}, which translates to createElement({ ..., onclick: this.foo, ...}), so there is lost binding right there.
class Dog {
constructor(name) {
this.name = name;
}
giveSound() {
console.log(`${this.name} says woof`);
}
giveAlert() {
console.log("I am alert");
const f = this.giveSound;
f();
}
}
const woofie = new Dog("woofie");
woofie.giveSound();
woofie.giveAlert();
So if everything is an arrow function, then there is no such worry:
class Dog {
constructor(name) {
this.name = name;
}
giveSound = () => {
console.log(`${this.name} says woof`);
}
giveAlert = () => {
console.log("I am alert");
const f = this.giveSound;
f();
}
}
const woofie = new Dog("woofie");
woofie.giveSound();
woofie.giveAlert();
But is there any disadvantage?
There are a couple of disadvantages, but as you've pointed out, there's also an advantage, so it's really up to you.
The two main disadvantages I'm aware of are:
Every instance gets its own function objects for each method (three months = three function objects per instance), rather than sharing via the prototype. That means:
You create a bunch more objects when you create the instance (the function code is shared, but each instance gets its own function objects), and
Inheriting may be trickier
It makes the methods harder to mock for testing purposes, because they're not on the prototype, they're built into each instance.
I'm currently studying Javascript and saw that we can define members of an object in its prototype instead of in the object's constructor since it makes the objects lighter because they don't carry the method code in every instance.
I can see how variables can work badly if all objects of this constructor point to the same variable field, but methods shouldn't change too much or at all, so its not a problem to share them.
Is there a reason not to define methods on the prototype rather than the object's constructor?
One reason why one might prefer putting methods on the instance itself would be to ensure the correct this context while adding a method concisely. Getting this to work properly is a very common problem in JavaScript.
For example:
class Foo {
i = 0;
clickHandler = () => console.log(this.i++);
}
const f = new Foo();
window.onclick = f.clickHandler;
This is a common pattern with class components in React. If one put the method on the prototype instead, it could sometimes get a bit uglier:
class Foo {
i = 0;
clickHandler() {
console.log(this.i++);
}
}
const f = new Foo();
window.onclick = () => f.clickHandler();
Another common way of dealing with this is to move a bound method from the prototype to the instance in the constructor:
class Foo {
i = 0;
constructor() {
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler() {
console.log(this.i++);
}
}
const f = new Foo();
window.onclick = () => f.clickHandler();
Is that reason to prefer one over the other? That's up to you, but its one arguable advantage to keep in mind.
Just an idea from me - there is a way of dealing with the "proper" execution context of e.g. click handlers on prototype level as well. Consider the following example:
class AbstractClickHandler {
// the "proper" this is ensured via closure over the actual implementation
clickHandler() {
return (...args) => {
this.handleClick.apply(this, args)
}
}
// no-op in base class
handleClick() {
}
}
class ClickHandler extends AbstractClickHandler {
constructor(data) {
super()
this.data = data
}
// actual implementation of the handler logic
handleClick(arg1, arg2) {
console.log(`Click handled with data ${this.data} and arguments ${arg1}, ${arg2}`)
}
}
const instance = new ClickHandler(42)
const handler = instance.clickHandler()
handler.call(null, 'one', 'two')
This way, there is no need to define a bound handler in every concerned constructor.
I recently search in the code of the library of knockout to find how observables are able to create dependencies with computed functions when we call it.
In the source code, I found the function linked to observables creation:
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if (observable.isDifferent(_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
ko.subscribable.call(observable);
ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
if (DEBUG) observable._latestValue = _latestValue;
observable.peek = function() { return _latestValue };
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
ko.exportProperty(observable, 'peek', observable.peek);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
return observable;
}
What I think is very weird is the returns of 'observable' where I don't found any declaration of this variable. Sure that great men who created this library don't forget to declared it.
How it is possible to use a variable without declared it and prevent it to be put in a global scope?
My feeling is we can used a function declaration as a variable when this function declaration is declared inside another function but I'm really not sure about how it works.
Edit:
After searching on the web, I found this article.
In this article, the guy write this:
Use declarations, please
"In the code of unexperienced developers, functions are often declared by expressions:
... code ... var f = function() { ... } ...
Function Declarations are much more readable and shorter. Use them instead.
... code ... function f() { ... } ...
Besides, functions declared this way can be called before it’s definition.
Use expressions only if you mean it. E.g for conditional function definition."
Ok, Am I an unexperienced developer? I don't think so. I just don't read all the odds of Javascript. :)
observable is a variable. It is declared by a function declaration.
function observable() {
...
}
In Javascript, functions can also be returned. Within the function, he defines the function "observable" which is returned at the end of the function.
Sort to speak, functions are variables too. With a function inside.
In Java you could call methods to help you do some heavy lifting in the constructor, but javascript requires the method to be defined first, so I'm wondering if there's another way I could go about this or if I'm forced to call the method that does the heavy lifting after it's been defined. I prefer to keep instance functions contained within the Object/Class, and it feels weird that I would have to have the constructor at the very end of the object/class.
function Polynomials(polyString)
{
// instance variables
this.polys = [];
this.left = undefined;
this.right = undefined;
// This does not work because it's not yet declared
this.parseInit(polyString);
// this parses out a string and initializes this.left and this.right
this.parseInit = function(polyString)
{
//Lots of heavy lifting here (many lines of code)
}
// A lot more instance functions defined down here (even more lines of code)
// Is my only option to call it here?
}
Here's what I would do:
var Polynomials = function() {
// let's use a self invoking anonymous function
// so that we can define var / function without polluting namespace
// idea is to build the class then return it, while taking advantage
// of a local scope.
// constructor definition
function Polynomials( value1) (
this.property1 = value1;
instanceCount++;
// here you can use publicMethod1 or parseInit
}
// define all the public methods of your class on its prototype.
Polynomials.prototype = {
publicMethod1 : function() { /* parseInit()... */ },
getInstanceCount : function() ( return instanceCount; }
}
// you can define functions that won't pollute namespace here
// those are functions private to the class (that can't be accessed by inheriting classes)
function parseInit() {
}
// you can define also vars private to the class
// most obvious example is instance count.
var instanceCount = 0;
// return the class-function just built;
return Polynomials;
}();
Remarks:
Rq 1:
prototype functions are public methods available for each instance of the class.
var newInstance = new MyClass();
newInstance.functionDefinedOnPrototype(sameValue);
Rq2:
If you want truly 'private' variable, you have to got this way:
function Constructor() {
var privateProperty=12;
this.functionUsingPrivateProperty = function() {
// here you can use privateProperrty, it's in scope
}
}
Constructor.prototype = {
// here define public methods that uses only public properties
publicMethod1 : function() {
// here privateProperty cannot be reached, it is out of scope.
}
}
personally, I do use only properties (not private vars), and use the '' common convention to notify a property is private. So I can define every public method on the prototype.
After that, anyone using a property prefixed with '' must take his/her responsibility , it seems fair. :-)
For the difference between function fn() {} and var fn= function() {}, google or S.O. for this question, short answer is that function fn() {} gets the function defined and assigned its value in whole scope, when var get the var defined, but its value is only evaluated when code has run the evaluation.
Your 'instance variables' are declared on the 'this' object which if you're looking for a Java equivalent is a bit like making them public. You can declare variables with the var keyword which makes them more like private variables within your constructor function. Then they are subject to 'hoisting' which basically means they are regarded as being declared at the top of your function (or whatever scope they are declared in) even if you write them after the invoking code.
I would create a function declaration and then assign the variable to the function declaration. The reason being that JavaScript will hoist your function declarations.
So you could do this:
function Polynomials(polyString) {
// instance variables
this.polys = [];
this.left = undefined;
this.right = undefined;
// this parses out a string and initializes this.left and this.right
this.parseInit = parseInitFunc;
// This does not work because it's not yet declared
this.parseInit(polyString);
// A lot more instance functions defined down here (even more lines of code)
function parseInitFunc(polyString) {
console.log('executed');
}
// Is my only option to call it here?
}
That way your code stays clean.
jsFiddle
Well I tried to figure out is this possible in any way. Here is code:
a=function(text)
{
var b=text;
if (!arguments.callee.prototype.get)
arguments.callee.prototype.get=function()
{
return b;
}
else
alert('already created!');
}
var c=new a("test"); // creates prototype instance of getter
var d=new a("ojoj"); // alerts already created
alert(c.get()) // alerts test
alert(d.get()) // alerts test from context of creating prototype function :(
As you see I tried to create prototype getter. For what? Well if you write something like this:
a=function(text)
{
var b=text;
this.getText=function(){ return b}
}
... everything should be fine.. but in fact every time I create object - i create getText function that uses memory. I would like to have one prototypical function lying in memory that would do the same... Any ideas?
EDIT:
I tried solution given by Christoph, and it seems that its only known solution for now. It need to remember id information to retrieve value from context, but whole idea is nice for me :) Id is only one thing to remember, everything else can be stored once in memory. In fact you could store a lot of private members this way, and use anytime only one id. Actually this is satisfying me :) (unless someone got better idea).
someFunc = function()
{
var store = new Array();
var guid=0;
var someFunc = function(text)
{
this.__guid=guid;
store[guid++]=text;
}
someFunc.prototype.getValue=function()
{
return store[this.__guid];
}
return someFunc;
}()
a=new someFunc("test");
b=new someFunc("test2");
alert(a.getValue());
alert(b.getValue());
JavaScript traditionally did not provide a mechanism for property hiding ('private members').
As JavaScript is lexically scoped, you could always simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.
Of course, there are ways to work around this, but I wouldn't recommend it:
Foo = (function() {
var store = {}, guid = 0;
function Foo() {
this.__guid = ++guid;
store[guid] = { bar : 'baz' };
}
Foo.prototype.getBar = function() {
var privates = store[this.__guid];
return privates.bar;
};
Foo.prototype.destroy = function() {
delete store[this.__guid];
};
return Foo;
})();
This will store the 'private' properties in another object seperate from your Foo instance. Make sure to call destroy() after you're done wih the object: otherwise, you've just created a memory leak.
edit 2015-12-01: ECMAScript6 makes improved variants that do not require manual object destruction possible, eg by using a WeakMap or preferably a Symbol, avoiding the need for an external store altogether:
var Foo = (function() {
var bar = Symbol('bar');
function Foo() {
this[bar] = 'baz';
}
Foo.prototype.getBar = function() {
return this[bar];
};
return Foo;
})();
With modern browsers adopting some ES6 technologies, you can use WeakMap to get around the GUID problem. This works in IE11 and above:
// Scope private vars inside an IIFE
var Foo = (function() {
// Store all the Foos, and garbage-collect them automatically
var fooMap = new WeakMap();
var Foo = function(txt) {
var privateMethod = function() {
console.log(txt);
};
// Store this Foo in the WeakMap
fooMap.set(this, {privateMethod: privateMethod});
}
Foo.prototype = Object.create(Object.prototype);
Foo.prototype.public = function() {
fooMap.get(this).p();
}
return Foo;
}());
var foo1 = new Foo("This is foo1's private method");
var foo2 = new Foo("This is foo2's private method");
foo1.public(); // "This is foo1's private method"
foo2.public(); // "This is foo2's private method"
WeakMap won't store references to any Foo after it gets deleted or falls out of scope, and since it uses objects as keys, you don't need to attach GUIDs to your object.
Methods on the prototype cannot access "private" members as they exist in javascript; you need some kind of privileged accessor. Since you are declaring get where it can lexically see b, it will always return what b was upon creation.
After being hugely inspired by Christoph's work-around, I came up with a slightly modified concept that provides a few enhancements. Again, this solution is interesting, but not necessarily recommended. These enhancements include:
No longer need to perform any setup in the constructor
Removed the need to store a public GUID on instances
Added some syntactic sugar
Essentially the trick here is to use the instance object itself as the key to accessing the associated private object. Normally this is not possible with plain objects since their keys must be strings. However, I was able to accomplish this using the fact that the expression ({} === {}) returns false. In other words the comparison operator can discern between unique object instances.
Long story short, we can use two arrays to maintain instances and their associated private objects:
Foo = (function() {
var instances = [], privates = [];
// private object accessor function
function _(instance) {
var index = instances.indexOf(instance), privateObj;
if(index == -1) {
// Lazily associate instance with a new private object
instances.push(instance);
privates.push(privateObj = {});
}
else {
// A privateObject has already been created, so grab that
privateObj = privates[index];
}
return privateObj;
}
function Foo() {
_(this).bar = "This is a private bar!";
}
Foo.prototype.getBar = function() {
return _(this).bar;
};
return Foo;
})();
You'll notice the _ function above. This is the accessor function to grab ahold of the private object. It works lazily, so if you call it with a new instance, it will create a new private object on the fly.
If you don't want to duplicate the _ code for every class, you can solve this by wrapping it inside a factory function:
function createPrivateStore() {
var instances = [], privates = [];
return function (instance) {
// Same implementation as example above ...
};
}
Now you can reduce it to just one line for each class:
var _ = createPrivateStore();
Again, you have to be very careful using this solution as it can create memory leaks if you do not implement and call a destroy function when necessary.
Personally, I don't really like the solution with the guid, because it forces the developer to declare it in addition to the store and to increment it in the constructor. In large javascript application developers might forget to do so which is quite error prone.
I like Peter's answer pretty much because of the fact that you can access the private members using the context (this). But one thing that bothers me quite much is the fact that the access to private members is done in a o(n) complexity. Indeed finding the index of an object in array is a linear algorithm. Consider you want to use this pattern for an object that is instanciated 10000 times. Then you might iterate through 10000 instances each time you want to access a private member.
In order to access to private stores in a o(1) complexity, there is no other way than to use guids. But in order not to bother with the guid declaration and incrementation and in order to use the context to access the private store I modified Peters factory pattern as follow:
createPrivateStore = function () {
var privates = {}, guid = 0;
return function (instance) {
if (instance.__ajxguid__ === undefined) {
// Lazily associate instance with a new private object
var private_obj = {};
instance.__ajxguid__ = ++guid;
privates[instance.__ajxguid__] = private_obj;
return private_obj;
}
return privates[instance.__ajxguid__];
}
}
The trick here is to consider that the objects that do not have the ajxguid property are not yet handled. Indeed, one could manually set the property before accessing the store for the first time, but I think there is no magical solution.
I think real privacy is overrated. Virtual privacy is all that is needed. I think the use of _privateIdentifier is a step in the right direction but not far enough because you're still presented with a listing of all the _privateIdentifiers in intellisense popups. A further and better step is to create an object in the prototype and/or constructor function for segregating your virtually private fields and methods out of sight like so:
// Create the object
function MyObject() {}
// Add methods to the prototype
MyObject.prototype = {
// This is our public method
public: function () {
console.log('PUBLIC method has been called');
},
// This is our private method tucked away inside a nested privacy object called x
x: {
private: function () {
console.log('PRIVATE method has been called');
}
},
}
// Create an instance of the object
var mo = new MyObject();
now when the coder types "mo." intellisense will only show the public function and "x". So all the private members are not shown but hidden behind "x" making it more unlikely for a coder to accidentally call a private member because they'll have to go out of their way and type "mo.x." to see private members. This method also avoids the intellisense listing from being cluttered with multiple private member names, hiding them all behind the single item "x".
I know this thread is really really old now, but thought this solution might be of interest to anyone passing by:
const Immutable = function ( val ) {
let _val = val;
this.$ = {
_resolve: function () {
return _val;
}
};
};
Immutable.prototype = {
resolve: function () {
return this.$._resolve();
}
};
Essentially hiding the internal _val from being manipulated and making an instance of this object immutable.
I have created a new library for enabling private methods on the prototype chain.
https://github.com/TremayneChrist/ProtectJS
Example:
var MyObject = (function () {
// Create the object
function MyObject() {}
// Add methods to the prototype
MyObject.prototype = {
// This is our public method
public: function () {
console.log('PUBLIC method has been called');
},
// This is our private method, using (_)
_private: function () {
console.log('PRIVATE method has been called');
}
}
return protect(MyObject);
})();
// Create an instance of the object
var mo = new MyObject();
// Call its methods
mo.public(); // Pass
mo._private(); // Fail