I'm trying to practice JS OOP, particularly prototype inheritance, and I can't figure out why this JS Fiddle is returning undefined. Code below:
function Shape(name, edges) {
this.Name = name;
this.Edges = edges;
}
Shape.prototype.toString = function(){ return "Shape: " + this.Name;};
function Circle(radius) {
this.Radius = radius;
}
Circle.prototype.Area = function(){
return Math.PI * Math.pow(this.Radius, 2);
};
Circle.prototype = new Shape("Circle", 1);
Circle.prototype.constructor = Circle;
var circle = new Circle(5);
console.log(circle);
console.log(circle.toString());
console.log(circle.Area);
Could anyone shed some light on this please?
Executing your code, I get the following output:
Circle { Radius=5, Name="Circle", Edges=1 }
Shape: Circle
function()
So, there is no undefined here. However, I can imagine you wanted to see the calculated area be printed on the console instead of function().
This can be done by actually calling the Area function, like so:
console.log(circle.Area());
After making this modification (see JSFiddle), you get the correct result:
78.53981633974483
Explanation: In your implementation, you were only accessing the function object, which printed function(), instead of calling the function, which really calculates the desired value.
EDIT
As from your comment, I believe your question is a duplicate of this one. From the details given in this answer, I was able to get the following working:
function Circle(radius) {
this.Name = "Circle";
this.Edges = 1;
this.Radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.Area = function () {
return Math.PI * Math.pow(this.Radius, 2);
};
However, my JS skills are limited, so this might have a flaw or two. For more advanced inheritance, you may take a look at the accepted answer in the question I referenced above for hints on frameworks that would be worth using.
If you are calling Area function to get the area of circle then you need to call it like this
console.log(circle.Area())
JS Fiddle
None of your logs show undefined.
If you're testing in your developer's console, you'll find a final return value at the end of your input. This value is often undefined, and has nothing to do with your code.
I figured it out.
But its with thanks to everyone on this thread actually. It took a while for it dawn on me and its actually a rookie mistake.
I assigned the prototype function Area to object circle, before inheriting the base Shape prototype.
The section in question is now like so:
function Circle(radius) {
this.Radius = radius;
}
Circle.prototype = new Shape("Circle", 1);
Circle.prototype.constructor = Circle;
Circle.prototype.Area = function () {
return Math.PI * Math.pow(this.Radius, 2);
};
//creating the main Object variables with static Propertys
var MySystem={
Utility:{},
AppDbSystem:{
connecterObj:"",
objCollection:new Array(),
sendObjCollection:null,
phpGridCollection:null
},
OutManager:{},
DbIndex:{},
GoDb:{},
Ioform:{},
ListView:{},
WindowSystem:{},
AngularSystem:{
objCollection:null
}
}
//the parent class (top of the chain)
MySystem.GoDb.GoDb=function(){
var that=this;
this.namespace;
this.speicher;
this.initGoDb=function(table,group,indexArr,readOnly){
that.speicher=table;
}
this.showS=function(){
alert(that.speicher);
}
this.setNamespace=function(ns){
that.namespace=ns;
}
this.getNamespace=function(){
return that.namespace;
}
}
//ListView second Class of the Chain
MySystem.ListView.ListView=function(){
var that=this;
MySystem.GoDb.GoDb.apply(this); //IMPORTANT to make it as an Instance
this.initListView=function(submitIndex,idArr,methodActionArr){
that.initGoDb(submitIndex);
}
}
MySystem.ListView.ListView.prototype=new MySystem.GoDb.GoDb();
//The Child Class
MySystem.ListView.ListStandard=function(){
var that=this;
MySystem.ListView.ListView.apply(this);
this.init=function(elementYArr,attrs,methodActionArr,idArr,tableId,styleArr,styleArrTr,styleArrTd,withNumbers,submitIndex){
that.initListView(elementYArr);
}
}
MySystem.ListView.ListStandard.prototype=new MySystem.ListView.ListView();
//now use it
var test=new MySystem.ListView.ListStandard();
var test2=new MySystem.ListView.ListStandard();
test.init("eazy");
test.showS();
test2.init("second obj");
test2.showS();
test.showS();
Look at http://www.zipcon.net/~swhite/docs/computers/languages/object_oriented_JS/inheritance.html
And dont forget to do the apply call.
MySystem.ListView.ListView.apply(this);
Otherwise the Object propertys are static and not inheritable.
[Edited: vector2d and vector3d are not good examples. I am now using pt and ptMass instead.]
I have been searching answers for this but there seems no good solution available.
Suppose I have an object as below.
function pt(x,y){
this.x = x;
this.y = y;
}
Now, I would like to have a point mass as below.
function ptMass(x,y,m){
this.x = x;
this.y = y;
this.m = m;
}
It is better to use inheritance to create the ptMass class.
I am currently using the following way to do it.
function ptMass(x,y,m){
pt.apply(this.arguments);
this.m = m;
}
Is there a way of doing this with prototype?
I have tried the following but it doesn't work.
pt = function(m){this.m = m};
ptMass.prototype = new pt();
One more question, what is the advance of using prototypical inheritance?
First, why is it better to inherit it?
I get several arguments for inheritance, though I prefer composition (modules/components and dependency-injection) myself.
Second, you get reuse out of doing:
function Vector2D (x, y) {
this.x = x;
this.y = y;
}
function Vector3D (x, y, z) {
Vector2D.call(this, x, y);
this.z = z;
}
Third, in a large-scale JS app, creating tens of thousands (or millions) of polygons, the extra function calls are just going to slow it down, unnecessarily.
Fourth, you can't use
Vector3D.prototype = new Vector2D();
First, you're not initializing x and y to anything inside of the Vector2D.
Second, prototype is meant to hold STATIC properties and functions, if you're coming from other languages.
Even if you did initialize Vector2D, it would still be the exact same Vector2D for every instance of your Vector3D class.
Why not just:
var point2D = function (x, y) {
return { x : x,
y : y };
},
point3D = function (x, y, z) {
return { x : x,
y : y,
z : z };
};
...and when you have those particular building-blocks as your base elements, compose different modules which use them?
EDIT
function anObj (x, y) {
var privateFunc = function () { return y; };
return {
x : x,
method : function () { return privateFunc(); }
};
}
var myObj = anObj(1, 2);
myObj.x; // 1
myObj.method(); // 2
The upside here is that you've now got private variables (privateFunc and y).
The downside is that in terms of memory-usage, each instance of your object needs to have its OWN copy of any private methods.
So if you're making hundreds of thousands of these objects (vertices/polygons, for example), and they don't NEED to have private state, this isn't the method to use.
If, however, you're making players or enemies, or controllers, or anything which you DON'T want tampered with, then you DO want to use a method like this (or more advanced).
If you have a situation where you might want STATIC data / methods which are also 100% private, then you should try a format like this:
var objectMaker = (function () {
var staticData = 32,
staticFunc = function (num) { return num + staticData; };
return function (x, y) {
var privateData = 12,
privateMethod = function (num) {
return y + privateData + staticFunc(num);
};
return { x : x,
method : function (num) { return privateMethod(num); }
};
};
}());
var myObj = objectMaker(3, 4);
myObj.x; // 3;
myObj.method(12); // 12 + y(y === 4) + privateData + staticData;
So what we've done here is we've got an immediately-firing function (it fires as soon as its defined, and returns the value of the function to the variable).
So in our particular case, this function immediately returns the actual function that we want to use to make new instances.
The private variables and functions that are inside of the immediate function (not the constructor we return) are static, in that every instance you create will have access to the exact same functions/data inside of that closure.
The downside is that those static functions have NO access to private (or even instance-specific) data.
This means that you have to pass your values into the static function, and catch the return from the static function, as you can't rely on the static methods to modify instance values (technically, you can modify objects/arrays, directly if you pass them into the function, but otherwise you must catch return values).
Now you can have plenty of helper functions which are shared amongst instances (lower memory), while still being private and secure.
If what you want is public properties, public methods, and static methods/properties, THEN you can access them like so:
var Obj = function (x, y) {
this.x = x;
this.per_instance_method = function () { return y; };
};
Obj.prototype.staticData = { z : 32 };
Obj.prototype.staticMethod = function () { return this.x + this.staticData.z; };
var myObj = new Obj(3, 4);
myObj.staticMethod();
...just don't expect any prototype method to have access to any instance's private data (like y).
No, your first one was nearly correct:
function vector3d(x,y,z){
vector2d.apply(this, arguments);
// you might also use vector2d.apply(this, [].slice.call(arguments, 0,2));
// or simpler vector2d.call(this, x, y);
this.z=z;
}
So yes, you must call it from the constructor. Calling it once to create a prototype object would set up inheritance correctly, but create an instance of vector2D - which you neither need nor want. It might even cause harm. Have a look at the detailed answers on What is the reason [not] to use the 'new' keyword [for inheritance]?.
Is there a way of doing this with prototype?
vector3d.prototype = Object.create(vector2d.prototype);
will make the prototype object, from which all instances of vector3 inherit, inherit from the prototype object of vector2d. I'm not sure whether you need that, none of the usual twodimensional methods would apply on a threedimensional vector.
what is the advance of using prototypical inheritance?
Benefits of prototypal inheritance over classical?
What does it mean that Javascript is a prototype based language?
I was reading Crockford's tutorial http://javascript.crockford.com/private.html.
private variables are implemented by function inside constructor that makes possible to associate private variables to closure.
Generally javascript libraries are open, so anyone can see and modify the private variables by modifying the inner function of constructor thru instances/objects. like this:
c1.radius = function (){return 500;};
Be more precisly: In real OOPS no one can modify private variable by objects but here we can.
Can anyone please suggest me the way to make it full tamper proof like JAVA or C?
function Circle(radius) {
this.radius = function(){ return radius;}
}
Circle.prototype = {
constructor: Circle,
area: function(){
return (Math.PI)* (Math.pow(this.radius(),2));
}
};
c1 = new Circle(5);
console.log(c1.radius());
console.log(c1.area());
c1.radius = function (){return 500;};
1st off, don't worry too much about making it tamper proof. If somebody really wants to, they'll be able to access what they want.
2ndly, you can't really do this unless you're using ECMAScript 5 (IE9+, Safari 5+, Chrome 7+, FF 4+). If you're using an ES5 browser, you can do what you want using the Object.defineProperty method, or using Object.create:
function Circle(radius) {
Object.defineProperty(this, 'radius', {
value: radius
});
}
NOTE: When using Object.create or Object.defineProperty, properties are by default non-writable, non-configurable (type can't be changed and property can't be deleted), and non-enumerable (won't show up in for(var x in obj) constructs).
What about this?
function oTest(){
var a; // "private"
this.b; // "public"
this.get_a = function(){
return a
)
}
var aTest = new oTest();
aTest.private_get = function(){
return a
}
aTest.private_get() // ReferenceError: a is not defined
aTest.get_a() // works
I'm not sure I fully understand your question, but a is only available to the original set of methods provided.
You might want to look at traits.js. In the following example radius and area are immutable or tamper proof.
function TCircle(radius) {
return Trait.create(
Object.prototype,
Trait({
radius: radius,
area: function() {
return (Math.PI) * (Math.pow(this.radius, 2));
}
}));
}
var circle = TCircle(5);
console.log(circle.area()); // 78.53981633974483
circle.radius = null;
console.log(circle.area()); // 78.53981633974483
circle.radius = 99;
console.log(circle.area()); // 78.53981633974483
If you want a mutable object then you would use Object.create rather than Trait.create above.
I wonder about what the best way is to create an JavaScript object that has properties and methods.
I have seen examples where the person used var self = this and then uses self. in all functions to make sure the scope is always correct.
Then I have seen examples of using .prototype to add properties, while others do it inline.
Can someone give me a proper example of a JavaScript object with some properties and methods?
There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.
The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)
Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.
function Shape(x, y) {
this.x= x;
this.y= y;
}
We can add methods to the instance created by new Shape by writing them to the prototype lookup of this constructor function:
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype property:
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= new Shape();
before adding methods to it:
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
This example will work and you will see code like it in many tutorials. But man, that new Shape() is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x and y become undefined and are assigned to the prototype's this.x and this.y. If the constructor function were doing anything more complicated, it would fall flat on its face.
So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:
function subclassOf(base) {
_subclassOf.prototype= base.prototype;
return new _subclassOf();
}
function _subclassOf() {};
This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.prototype= subclassOf(Shape);
instead of the new Shape() wrongness. We now have an acceptable set of primitives to built classes.
There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:
Function.prototype.subclass= function(base) {
var c= Function.prototype.subclass.nonconstructor;
c.prototype= base.prototype;
this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};
...
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.subclass(Shape);
Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply, but still you have to write out:
function Point() {
Shape.apply(this, arguments);
}
Point.subclass(Shape);
So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:
function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!
Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass, turning it round and letting the base class's Function spit out subclasses:
Function.prototype.makeSubclass= function() {
function Class() {
if ('_init' in this)
this._init.apply(this, arguments);
}
Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};
...
Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
Point= Shape.makeSubclass();
Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
Shape.prototype._init.call(this, x, y);
this.r= r;
};
...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass to take and remember a class name and provide a default toString using it. Maybe you want to make the constructor detect when it has accidentally been called without the new operator (which would otherwise often result in very annoying debugging):
Function.prototype.makeSubclass= function() {
function Class() {
if (!(this instanceof Class))
throw('Constructor called without "new"');
...
Maybe you want to pass in all the new members and have makeSubclass add them to the prototype, to save you having to write Class.prototype... quite so much. A lot of class systems do that, eg:
Circle= Shape.makeSubclass({
_init: function(x, y, z) {
Shape.prototype._init.call(this, x, y);
this.r= r;
},
...
});
There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.
The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:
function Shape(x, y) {
var that= this;
this.x= x;
this.y= y;
this.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
}
function Circle(x, y, r) {
var that= this;
Shape.call(this, x, y);
this.r= r;
var _baseToString= this.toString;
this.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+that.r;
};
};
var mycircle= new Circle();
Now every single instance of Shape will have its own copy of the toString method (and any other methods or other class members we add).
The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.
[Also because there is no inheritance here, the instanceof operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof working.]
The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this in method calls, which has the upshot that if you detach a method from its owner:
var ts= mycircle.toString;
alert(ts());
then this inside the method won't be the Circle instance as expected (it'll actually be the global window object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout, onclick or EventListener in general.
With the prototype way, you have to include a closure for every such assignment:
setTimeout(function() {
mycircle.move(1, 1);
}, 1000);
or, in the future (or now if you hack Function.prototype) you can also do it with function.bind():
setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);
if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that or self, though personally I would advise against the latter as self already has another, different meaning in JavaScript). You don't get the arguments 1, 1 in the above snippet for free though, so you would still need another closure or a bind() if you need to do that.
There are lots of variants on the closure method too. You may prefer to omit this completely, creating a new that and returning it instead of using the new operator:
function Shape(x, y) {
var that= {};
that.x= x;
that.y= y;
that.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
return that;
}
function Circle(x, y, r) {
var that= Shape(x, y);
that.r= r;
var _baseToString= that.toString;
that.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+r;
};
return that;
};
var mycircle= Circle(); // you can include `new` if you want but it won't do anything
Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.
But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.
[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]
I use this pattern fairly frequently - I've found that it gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.
var Foo = function()
{
var privateStaticMethod = function() {};
var privateStaticVariable = "foo";
var constructor = function Foo(foo, bar)
{
var privateMethod = function() {};
this.publicMethod = function() {};
};
constructor.publicStaticMethod = function() {};
return constructor;
}();
This uses an anonymous function that is called upon creation, returning a new constructor function. Because the anonymous function is called only once, you can create private static variables in it (they're inside the closure, visible to the other members of the class). The constructor function is basically a standard Javascript object - you define private attributes inside of it, and public attributes are attached to the this variable.
Basically, this approach combines the Crockfordian approach with standard Javascript objects to create a more powerful class.
You can use it just like you would any other Javascript object:
Foo.publicStaticMethod(); //calling a static method
var test = new Foo(); //instantiation
test.publicMethod(); //calling a method
Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:
function Person() {
this.name = "John";
return this;
}
var person = new Person();
alert("name: " + person.name);**
In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.
To continue off of bobince's answer
In es6 you can now actually create a class
So now you can do:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
So extend to a circle (as in the other answer) you can do:
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
Ends up a bit cleaner in es6 and a little easier to read.
Here is a good example of it in action:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
let c = new Circle(1, 2, 4);
console.log('' + c, c);
You can also do it this way, using structures :
function createCounter () {
var count = 0;
return {
increaseBy: function(nb) {
count += nb;
},
reset: function {
count = 0;
}
}
}
Then :
var counter1 = createCounter();
counter1.increaseBy(4);
Another way would be http://jsfiddle.net/nnUY4/
(i dont know if this kind of handling object creation and revealing functions follow any specific pattern)
// Build-Reveal
var person={
create:function(_name){ // 'constructor'
// prevents direct instantiation
// but no inheritance
return (function() {
var name=_name||"defaultname"; // private variable
// [some private functions]
function getName(){
return name;
}
function setName(_name){
name=_name;
}
return { // revealed functions
getName:getName,
setName:setName
}
})();
}
}
// … no (instantiated) person so far …
var p=person.create(); // name will be set to 'defaultname'
p.setName("adam"); // and overwritten
var p2=person.create("eva"); // or provide 'constructor parameters'
alert(p.getName()+":"+p2.getName()); // alerts "adam:eva"
Creating an object
The easiest way to create an object in JavaScript is to use the following syntax :
var test = {
a : 5,
b : 10,
f : function(c) {
return this.a + this.b + c;
}
}
console.log(test);
console.log(test.f(3));
This works great for storing data in a structured way.
For more complex use cases, however, it's often better to create instances of functions :
function Test(a, b) {
this.a = a;
this.b = b;
this.f = function(c) {
return this.a + this.b + c;
};
}
var test = new Test(5, 10);
console.log(test);
console.log(test.f(3));
This allows you to create multiple objects that share the same "blueprint", similar to how you use classes in eg. Java.
This can still be done more efficiently, however, by using a prototype.
Whenever different instances of a function share the same methods or properties, you can move them to that object's prototype. That way, every instance of a function has access to that method or property, but it doesn't need to be duplicated for every instance.
In our case, it makes sense to move the method f to the prototype :
function Test(a, b) {
this.a = a;
this.b = b;
}
Test.prototype.f = function(c) {
return this.a + this.b + c;
};
var test = new Test(5, 10);
console.log(test);
console.log(test.f(3));
Inheritance
A simple but effective way to do inheritance in JavaScript, is to use the following two-liner :
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
That is similar to doing this :
B.prototype = new A();
The main difference between both is that the constructor of A is not run when using Object.create, which is more intuitive and more similar to class based inheritance.
You can always choose to optionally run the constructor of A when creating a new instance of B by adding adding it to the constructor of B :
function B(arg1, arg2) {
A(arg1, arg2); // This is optional
}
If you want to pass all arguments of B to A, you can also use Function.prototype.apply() :
function B() {
A.apply(this, arguments); // This is optional
}
If you want to mixin another object into the constructor chain of B, you can combine Object.create with Object.assign :
B.prototype = Object.assign(Object.create(A.prototype), mixin.prototype);
B.prototype.constructor = B;
Demo
function A(name) {
this.name = name;
}
A.prototype = Object.create(Object.prototype);
A.prototype.constructor = A;
function B() {
A.apply(this, arguments);
this.street = "Downing Street 10";
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
function mixin() {
}
mixin.prototype = Object.create(Object.prototype);
mixin.prototype.constructor = mixin;
mixin.prototype.getProperties = function() {
return {
name: this.name,
address: this.street,
year: this.year
};
};
function C() {
B.apply(this, arguments);
this.year = "2018"
}
C.prototype = Object.assign(Object.create(B.prototype), mixin.prototype);
C.prototype.constructor = C;
var instance = new C("Frank");
console.log(instance);
console.log(instance.getProperties());
Note
Object.create can be safely used in every modern browser, including IE9+. Object.assign does not work in any version of IE nor some mobile browsers. It is recommended to polyfill Object.create and/or Object.assign if you want to use them and support browsers that do not implement them.
You can find a polyfill for Object.create here
and one for Object.assign here.
When one uses the trick of closing on "this" during a constructor invocation, it's in order to write a function that can be used as a callback by some other object that doesn't want to invoke a method on an object. It's not related to "making the scope correct".
Here's a vanilla JavaScript object:
function MyThing(aParam) {
var myPrivateVariable = "squizzitch";
this.someProperty = aParam;
this.useMeAsACallback = function() {
console.log("Look, I have access to " + myPrivateVariable + "!");
}
}
// Every MyThing will get this method for free:
MyThing.prototype.someMethod = function() {
console.log(this.someProperty);
};
You might get a lot out of reading what Douglas Crockford has to say about JavaScript. John Resig is also brilliant. Good luck!
Closure is versatile. bobince has well summarized the prototype vs. closure approaches when creating objects. However you can mimic some aspects of OOP using closure in a functional programming way. Remember functions are objects in JavaScript; so use function as object in a different way.
Here is an example of closure:
function outer(outerArg) {
return inner(innerArg) {
return innerArg + outerArg; //the scope chain is composed of innerArg and outerArg from the outer context
}
}
A while ago I came across the Mozilla's article on Closure. Here is what jump at my eyes: "A closure lets you associate some data (the environment) with a function that operates on that data. This has obvious parallels to object oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods". It was the very first time I read a parallelism between closure and classic OOP with no reference to prototype.
How?
Suppose you want to calculate the VAT of some items. The VAT is likely to stay stable during the lifetime of an application. One way to do it in OOP (pseudo code):
public class Calculator {
public property VAT { get; private set; }
public Calculator(int vat) {
this.VAT = vat;
}
public int Calculate(int price) {
return price * this.VAT;
}
}
Basically you pass a VAT value into your constructor and your calculate method can operate upon it via closure.
Now instead of using a class/constructor, pass your VAT as an argument into a function. Because the only stuff you are interested in is the calculation itself, returns a new function, which is the calculate method:
function calculator(vat) {
return function(item) {
return item * vat;
}
}
var calculate = calculator(1.10);
var jsBook = 100; //100$
calculate(jsBook); //110
In your project identify top-level values that are good candidate of what VAT is for calculation. As a rule of thumb whenever you pass the same arguments on and on, there is a way to improve it using closure. No need to create traditional objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
A Pattern That Serves Me Well
var Klass = function Klass() {
var thus = this;
var somePublicVariable = x
, somePublicVariable2 = x
;
var somePrivateVariable = x
, somePrivateVariable2 = x
;
var privateMethod = (function p() {...}).bind(this);
function publicMethod() {...}
// export precepts
this.var1 = somePublicVariable;
this.method = publicMethod;
return this;
};
First, you may change your preference of adding methods to the instance instead of the constructor's prototype object. I almost always declare methods inside of the constructor because I use Constructor Hijacking very often for purposes regarding Inheritance & Decorators.
Here's how I decide where which declarations are writ:
Never declare a method directly on the context object (this)
Let var declarations take precedence over function declarations
Let primitives take precedence over objects ({} and [])
Let public declarations take precedence over private declarations
Prefer Function.prototype.bind over thus, self, vm, etc
Avoid declaring a Class within another Class, unless:
It should be obvious that the two are inseparable
The Inner class implements The Command Pattern
The Inner class implements The Singleton Pattern
The Inner class implements The State Pattern
The Inner Class implements another Design Pattern that warrants this
Always return this from within the Lexical Scope of the Closure Space.
Here's why these help:
Constructor Hijacking
var Super = function Super() {
...
this.inherited = true;
...
};
var Klass = function Klass() {
...
// export precepts
Super.apply(this); // extends this with property `inherited`
...
};
Model Design
var Model = function Model(options) {
var options = options || {};
this.id = options.id || this.id || -1;
this.string = options.string || this.string || "";
// ...
return this;
};
var model = new Model({...});
var updated = Model.call(model, { string: 'modified' });
(model === updated === true); // > true
Design Patterns
var Singleton = new (function Singleton() {
var INSTANCE = null;
return function Klass() {
...
// export precepts
...
if (!INSTANCE) INSTANCE = this;
return INSTANCE;
};
})();
var a = new Singleton();
var b = new Singleton();
(a === b === true); // > true
As you can see, I really have no need for thus since I prefer Function.prototype.bind (or .call or .apply) over thus. In our Singleton class, we don't even name it thus because INSTANCE conveys more information. For Model, we return this so that we can invoke the Constructor using .call to return the instance we passed into it. Redundantly, we assigned it to the variable updated, though it is useful in other scenarios.
Alongside, I prefer constructing object-literals using the new keyword over {brackets}:
Preferred
var klass = new (function Klass(Base) {
...
// export precepts
Base.apply(this); //
this.override = x;
...
})(Super);
Not Preferred
var klass = Super.apply({
override: x
});
As you can see, the latter has no ability to override its Superclass's "override" property.
If I do add methods to the Class's prototype object, I prefer an object literal -- with or without using the new keyword:
Preferred
Klass.prototype = new Super();
// OR
Klass.prototype = new (function Base() {
...
// export precepts
Base.apply(this);
...
})(Super);
// OR
Klass.prototype = Super.apply({...});
// OR
Klass.prototype = {
method: function m() {...}
};
Not Preferred
Klass.prototype.method = function m() {...};
I'd like to mention that we can use either a Title or a String to declare an Object.
There are different ways on calling each type of them. See below:
var test = {
useTitle : "Here we use 'a Title' to declare an Object",
'useString': "Here we use 'a String' to declare an Object",
onTitle : function() {
return this.useTitle;
},
onString : function(type) {
return this[type];
}
}
console.log(test.onTitle());
console.log(test.onString('useString'));
var Person = function (lastname, age, job){
this.name = name;
this.age = age;
this.job = job;
this.changeName = function(name){
this.lastname = name;
}
}
var myWorker = new Person('Adeola', 23, 'Web Developer');
myWorker.changeName('Timmy');
console.log("New Worker" + myWorker.lastname);
In addition to the accepted answer from 2009. If you can can target modern browsers, one can make use of the Object.defineProperty.
The Object.defineProperty() method defines a new property directly on
an object, or modifies an existing property on an object, and returns
the object.
Source: Mozilla
var Foo = (function () {
function Foo() {
this._bar = false;
}
Object.defineProperty(Foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (theBar) {
this._bar = theBar;
},
enumerable: true,
configurable: true
});
Foo.prototype.toTest = function () {
alert("my value is " + this.bar);
};
return Foo;
}());
// test instance
var test = new Foo();
test.bar = true;
test.toTest();
To see a desktop and mobile compatibility list, see Mozilla's Browser Compatibility list. Yes, IE9+ supports it as well as Safari mobile.
You can also try this
function Person(obj) {
'use strict';
if (typeof obj === "undefined") {
this.name = "Bob";
this.age = 32;
this.company = "Facebook";
} else {
this.name = obj.name;
this.age = obj.age;
this.company = obj.company;
}
}
Person.prototype.print = function () {
'use strict';
console.log("Name: " + this.name + " Age : " + this.age + " Company : " + this.company);
};
var p1 = new Person({name: "Alex", age: 23, company: "Google"});
p1.print();
Bascially there is no concept of class in JS so we use function as a class constructor which is relevant with the existing design patterns.
//Constructor Pattern
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.doSomething = function(){
alert('I am Happy');
}
}
Till now JS has no clue that you want to create an object so here comes the new keyword.
var person1 = new Person('Arv', 30, 'Software');
person1.name //Arv
Ref : Professional JS for web developers - Nik Z