Javascript fundamental clarification needed - javascript

I know little bit C# and now I have started working with JavaScript and I got some problems in understanding the fundamentals.
Here is my code sample:
function BaseFunc(x, y) {
this.X = x;
this.Y = y;
}
function DerivedFunc(x, y, z) {
this.Z = z;
BaseFunc.call(this, x, y);
}
DerivedFunc.prototype = new BaseFunc;
function Test() {
var d = DerivedFunc(1, 2, 3);
var b = new BaseFunc(4, 5);
d.sayHello();
b.sayHello();
}
DerivedFunc.prototype.sayHello = function () {
alert("Result is: " + (this.X + this.Y + this.Z));
}
In the above code I am trying to make an inheritance.
Everything looks good until I reach the line BaseFunc.call(this, x, y); this line is supposed to call base function but what is the use of this in this context.
Is it just to satisfy the signature of method call, how does it work ?
Second question is, in javascript we can add anything dynamically,
In my case I am adding a sayHello() property and assigning it with an anonymous function.
like DerivedFunc.prototype.sayHello, am I adding a property/method to BaseFunc or DerivedFunc, as it is added to prototype it should be added to BaseFunc as I understand it. But when I execute the above code I get error that sayHello is not defined.
Can someone please clarify me about what is going wrong, thanks?

Everything looks good until I reach the line BaseFunc.call(this, x, y); this line is supposed to call base function but what is the use of this in this context.
It's there so that within the call to BaseFunc, this has the same value it has in the call to DerivedFunc, so that the lines this.X = x; and such in BaseFunc are assigning to the correct instance. (Calling a function setting a specific value for this is what the .call and .apply methods of functions do.)
But when I execute the above code I get error that sayHello is not defined.
If it's d.sayHello where you're having the trouble, it's because you've missed out the new operator on the line d = DerivedFunc(1, 2, 3);. Since DerivedFunc, when just called as a function and not via new, doesn't have any return value, d will be undefined.
Note that the way you're doing inheritance, though common, has issues. The main issue is here:
DerivedFunc.prototype = new BaseFunc;
You're trying to use a function designed to create instances, and which accepts arguments, in order to create the prototype instance that DerivedFunc will assign to things. What then is BaseFunc supposed to do about the arguments that are missing? Then later, you call it again (from DerivedFunc) to initialize the instance. BaseFunc is doing double-duty.
Here's how you correct that, first the long-winded version:
function x() { }
x.prototype = BaseFunc.prototype;
DerivedFunc.prototype = new x;
DerivedFunc.prototype.constructor = DerivedFunc;
Or if you can rely on ES5's Object.create:
DerivedFunc.prototype = Object.create(BaseFunc.prototype);
DerivedFunc.prototype.constructor = DerivedFunc;
Now we're not calling BaseFunc to create the prototype, but we are still getting its prototype object as the underlying prototype of DerivedFunc's prototype object. We no longer have the problem of what to do with BaseFunc's arguments, and BaseFunc is only called in the way it's designed to be called: To initialize individual instances, not prototypes.
Naturally, rather than writing that for every time we want to have derived constructors, you'd have a helper script for it.
If you're interested in JavaScript inheritance hierarchies, you may want to look at my short Lineage script — not necessarily to use, but to understand how these things work. The page showing how to do things without the script and comparing to doing them with the script may be particularly useful.

Hi please go through the following. I hope it will give you some idea about inheritence and call()
<script type="text/javascript">
//inheritence
function parent() {
this.add = function (a, b) {
return a + b;
}
this.subtract = function (a, b) {
return a - b;
}
}
function child() {
this.display = function () {
alert(this.add(11, 23));
}
}
child.prototype = new parent(); //child extends parent.... inheritence
child.prototype.constructor = child; //resetting constructor property
var obj = new child();
obj.display();
/*
.call() and .apply()
They allow our objects to borrow methods from other objects and invoke them as their own
*/
var person = {
name: 'Kundan',
display: function(name) {
alert(this.name + ' welcomes ' + name);
}
};
person.display('Dipa'); //Kundan welcomes Dipa
var person1 = { name: 'Java Master' };
person.display.call(person1, 'Sachin'); //Java Master welcomes Sachin
//here person1 object is passed in the call function
//if we are using call inside a function and want to pass the same function object then this is passed in call function
/*
We can pass more parameters as follows
person.display.call(person1, 'a', 'b', 'c');
The method apply() works the same way as call() but with the difference that all parameters you want to pass to the method of the other object are passed as an array.
*/
person.display.apply(person1, ['a', 'b', 'c']);
</script>

Related

Understanding Function.call.bind - step-by-step

Everything started with this Question
Then an answer from #MinusFour
var slice = Function.call.bind(Array.prototype.slice);
I wanted to understand, whats happening under the hood,
my curiosity hence this Question.
what to achieve ? understanding of "Function.call.bind".
Step-by-step approach for the same
Started with MDN
NOTE : I am using NodeJS here
1)
var adder = new Function('a', 'b', 'return a + b');
console.log(adder(2, 6));
**OUTPUT **
8
This is expected, Nothing Fancy
2)
This is our end goal , calling function myFunc from the bounded
function (Function.call.bind(myFunc))
function myFunc(a, b) {
console.log(arguments.length, a, b, a + b);
}
3)
var adder = Function(myFunc);
console.log(adder.toString())
OUTPUT
function anonymous() { function myFunc(a, b) { console.log(a + b); } }
Expected! above code does nothing, because i am calling 'anonymous' ,
and it does nothing.
4)
var adder = Function.call(myFunc);
console.log(adder.toString())
OUTPUT
function anonymous() {
}
Expected!. '.call' calls 'Function', with 'this' set to 'myFunc' and with out any param or function body. so an empty anonymous function is the output. Now, I can do "var adder = Function.call(myFunc,myFunc);" to create the same function from step-3
So far so good
5)
var adder = Function.call.bind(myFunc);
console.log(adder.toString())
adder(2,6);
OUTPUT
function () { [native code] }
1 6 undefined NaN
Here first param is not passed to the 'myFunc' function.
this is taken as 'this' for function 'adder' (the bounded Function.call) ?
Now I understand(or did I misunderstood?) until now, but then
How does below code works ?
var slice = Function.call.bind(Array.prototype.slice);
function fn(){
var arr = slice(arguments);
}
in my case first param to adder is discarded(or Function.call consider it as 'this' for it), same should happen with slice above right ?
Anyway, i wanted to document it for a reference
I'm afraid you've gone off in slightly the wrong direction. This line:
var slice = Function.call.bind(Array.prototype.slice);
never calls Function and never arranges for it to be called later. The only thing Function is being used for there is its call property. Function could have been Object or Date or RegExp or any other function, or could have been Function.prototype; doesn't matter. Function.prototype would have been more direct and possibly less confusing.
This is a bit tricky to explain because it involves two layers of dealing with this, where this is different things at different times:
The call function calls functions with a specific this value you give it as its first argument, passing along any other arguments you give it. For example:
function foo(arg) {
console.log("this.name = " + this.name + ", arg = " + arg);
}
var obj = {name: "bar"};
foo.call(obj, "glarb"); // "this.name = bar, arg = glarb"
There, because we called call on foo, call called foo with this set to obj and passing along the "glarb" argment.
call knows what function it should call based on what this is during the call call. foo.call sets this during call to foo. That can be confusing, so let's diagram it:
foo.call(obj, "glarb") calls call:
call sees this = foo and the arguments obj and "glarb"
call calls this (which is foo):
foo sees this = obj and the single argument "glarb"
With regard to slice, you normally see call used with it used to create an array from something array-like that isn't really an array:
var divArray = Array.prototype.slice.call(document.querySelectorAll("div"));
or
var divArray = [].slice.call(document.querySelectorAll("div"));
There, we call call with this set to Array.prototype.slice (or [].slice, which is the same function) and passing in the collection returned by querySelectorAll as the first argument. call calls the function it sees as this, using its first argument as this for that call, and passing along any others.
So that's the first layer of this stuff.
bind is another function that functions have, and it's similar to call but different: Where call calls the target function with a given this and arguments, bind creates and returns a new function that will do that if you call it. Going back to our foo example:
function foo(arg) {
console.log("this.name = " + this.name + ", arg = " + arg);
}
var obj = {name: "bar"};
var fooWithObjAndGlarb = foo.bind(obj, "glarb");
fooWithObjAndGlarb(); // "this.name = bar, arg = glarb"
This is called binding things (obj and the "glarb" argument) to foo.
Unlike call, since bind creates a new function, we can add arguments later:
function foo(arg) {
console.log("this.name = " + this.name + ", arg = " + arg);
}
var obj = {name: "bar"};
var fooWithObj = foo.bind(obj);
fooWithObj("glarb"); // "this.name = bar, arg = glarb"
Okay, now we have all our working pieces. So what's happening in your code? Let's break it into parts:
// Get a reference to the `call` function from the `call` property
// on `Function`. The reason `Function` has a `call` property is that
// `Function` is, itself, a function, which means its prototype is
// `Function.prototype`, which has `call` on it.
var call = Function.call;
// Get a reference to the `slice` function from `Array.prototype`'s `slice` property:
var rawSlice = Array.prototype.slice;
// Create a *bound* copy of `call` that, when called, will call
// `call` with `this` set to `rawSlice`
var callBoundToSlice = call.bind(rawSlice);
(callBoundToSlice is just called slice in your question, but I'm using callBoundToSlice to avoid confusion.) Binding rawSlice to call was the first layer of this handling, determining what call will see as this. Calling callBoundToSlice will call call with this set to rawSlice. Then call will call the function it sees as this (rawSlice), using its first argument as the value for this during the call (the second layer of this handling) and passing on any further arguments.
So our forEach with a collection from querySelectorAll can now look like this:
callBoundToSlice(document.querySelectorAll("div")).forEach(function(div) {
// Each div here
});
That passes the collecton returned by querySelectorAll into callBoundToSlice, which calls call with this as rawSlice, which calls Array.prototype.slice with this set to the collection. Array.prototype.slice uses this to copy the array.
All of that said, using slice to turn array-like objects into true arrays is a bit out of date. ES2015 introduces the Array.from method, which can be shimmed/polyfilled on JavaScript engines that don't have it yet:
var divArray = Array.from(document.querySelectorAll("div"));

JavaScript - Class definition best practice [duplicate]

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 9 years ago.
I am wondering if there are any advantages of using any of these over the other, and which way should I go?
Constructor approach:
var Class = function () {
this.calc = function (a, b) {
return a + b;
};
};
Prototype approach:
var Class = function () {};
Class.prototype.calc = function (a, b) {
return a + b;
};
I don't like that, using the prototype, method definitions are separated from the class, and I'm not aware if there is any specific reason I should use this over just the first approach.
Also, is there any benefit of using a function literal to define a "class", over just function definition:
var Class = function () {};
vs
function Class () {};
Thanks!
Methods that inherit via the prototype chain can be changed universally for all instances, for example:
function Class () {}
Class.prototype.calc = function (a, b) {
return a + b;
}
// Create 2 instances:
var ins1 = new Class(),
ins2 = new Class();
// Test the calc method:
console.log(ins1.calc(1,1), ins2.calc(1,1));
// -> 2, 2
// Change the prototype method
Class.prototype.calc = function () {
var args = Array.prototype.slice.apply(arguments),
res = 0, c;
while (c = args.shift())
res += c;
return res;
}
// Test the calc method:
console.log(ins1.calc(1,1,1), ins2.calc(1,1,1));
// -> 3, 3
Notice how changing the method applied to both instances? This is because ins1 and ins2 share the same calc() function. In order to do this with public methods created during construction, you'd have to assign the new method to each instance that has been created, which is an awkward task. This is because ins1 and ins2 would have their own, individually created calc() functions.
Another side effect of creating methods inside the constructor is poorer performance. Each method has to be created every time the constructor function runs. Methods on the prototype chain are created once and then "inherited" by each instance. On the flip side of the coin, public methods have access to "private" variables, which isn't possible with inherited methods.
As for your function Class() {} vs var Class = function () {} question, the former is "hoisted" to the top of the current scope before execution. For the latter, the variable declaration is hoisted, but not the assignment. For example:
// Error, fn is called before the function is assigned!
fn();
var fn = function () { alert("test!"); }
// Works as expected: the fn2 declaration is hoisted above the call
fn2();
function fn2() { alert("test!"); }
The advantage of the prototype approach is efficiency. There is one calc() function object shared between all Class objects (by which I mean objects created by calling the Class constructor). The other way (assigning methods within the constructor) creates a new function object for every Class object, using more memory and taking more processing time when calling the Class constructor. However, this approach does have an advantage: the calc() method has access to local variables within the constructor, which you can use to your advantage:
function Class() {
var calcCallCount = 0;
this.calc = function (a, b) {
++calcCallCount;
alert("Calc called " + calcCallCount + " times");
return a + b;
};
};
Regarding var Class = function() {...} versus function Class() {...}, I generally prefer the latter is because it means the function has a name, which can be useful when debugging. The other difference is that the latter version (a function declaration) is hoisted, meaning that it is available everywhere within the scope in which it is defined, not just after the definition. However, some people prefer to use the former (a function expression) everywhere.
var YourClass = function(){
var privateField = "somevalue";
this.publicField = "somevalue";
this.instanceMethod1 = function(){
//you may access both private and public field from here:
//in order to access public field, you must use "this":
alert(privateField + "; " + this.publicField);
};
}
YourClass.prototype.instanceMethod2 = function(){
//you may access only public field 2 from this method, but not private fields:
alert(this.publicField);
//error: drawaback of prototype methods:
alert(privateField);
};
Advantages of prototype methods:
When you define methods via prototype, they are shared among all YourClass instances. As a result the total size of such instances is < than if you define methods in constructor; There are tests that show how method definition via prototype decrease the total size of html page and as a result a speed of its loading.
another advantage of methods, defined via prototype - is when you use inherited classes, you may override such methods and in the overriden method of the derived class you may invoke the method of base class with the same name, but with methods defined in constructor, you cannot do this.

differences between defining functions/methods in JS?

Here are 3 ways to address the key-value pair of objects constructed using constructor. What are the differences among these 3 ways in every describable aspects? (I would even like to enquiry about basic differences between function & method in terms of their functionality, usage, etc.)
function Person(name,age) {
this.name = name;
this.age = age;
}
var bob = new Person("Bob Smith", 30);
var me = new Person('Madhav Devkota', 55);
//===================================================
//A. Simple function
printPerson= function (p) {
console.log(p.name);
};
printPerson(bob); printPerson(me);
//===================================================
//B. Method I
printPerson = function(){
console.log(this.name) ;
};
bob.printPerson = printPerson; me.printPerson = printPerson;
bob.printPerson(); me.printPerson();
//=================================================
//C. Method II
this.printPerson = function() {
console.log(this.name);
};
bob.printPerson(); me.printPerson();
I would also add
// 0. No function
console.log(bob.name);
console.log(me.name);
It is the most basic way. You are doing something with you object properties directly.
A. Simple function
You are giving your code a name to improve semantics. Now you are describing what your code is intended to do.
You can access more properties and combine to create complex result without code repetition.
printPerson = function (p) {
console.log(p.name + ' is aged ' + p.age)
}
instead of No function
console.log(bob.name + ' is aged ' + bob.age);
console.log(me.name ' is aged ' + me.age);
B. Method I
Now your function is also a property of your object. Unlike simple function which works in scope where it is declared, your method it attached to your object and you can pass it around along with it. When invoked 'this' references the object from which method is invoked.
You can also do a 'nonsense' method like this:
printPerson = function(p){
console.log(p.name) ;
};
bob.printPerson = printPerson; me.printPerson = printPerson;
bob.printPerson(bob); me.printPerson(me);
C. Method II
This one is not quite right. It doesn't make sense in given context as 'this' is at that moment referencing Window object. At then end you are actually calling 'Method I' methods again.
Correct way to use it is in constructor function:
function Person(name,age) {
this.name = name;
this.age = age;
this.printPerson = function() {
console.log(this.name);
};
}
Now your objects have .printPerson() method as soon as they are created.
I could elaborate more if you wish but it's important to notice that function vs method difference is not too relevant at this level of code complexity. When your code gets more complex code organization becomes important. For 'next level' you should get more familiar with Javascript scoping and object inheritance.

JavaScript inheritance why do I need to call both fun.call and prototype = new Obj( )?

function Base(x) {
this.x = x;
this.sub = new (function Sub() {
this.method = function() {
return function() {**this.super.x**}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
var base = new Base(5);
console.log(base.sub.method()())
basically, in this example I'm trying to create an object Base who has a sub object sub, which has a 'method' that uses an anonymous function. The anonymous function needs the x but cannot take in any parameters..
Is there any way to access the this.x of Base?
At the beginning I tried the following.
This works well when Base is not inherited by other objects.
But in the following
"use strict";
function Base(x) {
var that = this;
this.sub = new (function Sub() {
this.method = function() {
return function() {
console.log(that); // displays Base *note[1]
return that.x;
}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
function Other() {
Base.call(this); // why do I need to call Base.call(this) ?
this.setX = function(x) {this.x = x;}
}
Other.prototype = new Base();
var other = new Other();
other.setX(5);
console.log(other.sub.method()()); // otherwise undefined?
Base is extended by Other, after struggles I figured out I need to call Base.call(this); in order to make it works. Otherwise console.log(other.sub.method()()); will be undefined.
If I put a console.log(that) at *note[1], it will actually says the that is a Base object even though I construct it using var other = new Other(); I guess the problem would be solved if that is an Other object? What am I misunderstanding here?
My question is why do I need to call Base.call(this)? Why does it works after calling it? Is there any better solution to this situation?
If I understand you correctly you'd like Base to have a Sub and Sub is aware of the Base instance?
At the moment you're declaring the Sub type over and over again every time you create a Base, not the most effective way of doing it. Maybe try something like this:
function Sub(baseInstance){
this.baseInstance = baseInstance;
}
Sub.prototype.displayBaseX=function(){
console.log('base.x in sub:', this.baseInstance.x);
};
function Base(){
this.x = 22;
this.sub = new Sub(this);
}
You should not create an instance of Parent to set prototype of Child, use Object.create instead.
As for Parent.call(this, arguments) that is to re use the constructor function of Parent in Child when inheriting. More info about that can be found here: https://stackoverflow.com/a/16063711/1641941
The reason why your code doesn't work without Base.call(this); is because Base constructor defines and creates it's Sub type and instance. Not re using the Base constructor code when creating a Other type would cause the Other type not to have a Sub instance.
Constructor code deals with instance specific members and prototype can hold members that are shared by all instances. So usually behavior (functions) and a value for immutable default data members (numbers, string, boolean) can be found on the prototype.
I'm not exactly sure what you're end goal is here. But to solve your scope issue, this seems to work.
"use strict";
function Base(x) {
this.sub = new (function Sub(_this) {
this.method = (function(_this) {
return function() {
return _this.x;
};
})(_this);
})(this);
}
function Other() {
Base.call(this); // why do I need to call Base.call(this) ?
this.setX = function(x) {this.x = x;}
}
Other.prototype = new Base();
var other = new Other();
other.setX(5);
console.log(other.sub.method()); // otherwise undefined?
And a fiddle.

Javascript Prototype: Replacement vs Addition [duplicate]

This question already has answers here:
this.constructor.prototype -- can't wholly overwrite, but can write individual props?
(2 answers)
Closed 8 years ago.
I'm working with a fairly simple Point2D data structure I built to be inheritable for say a Point3D in the future and I've followed all the guides and similar questions I can find, but none seem help with my issue.
I've defined Point2D as follows:
function Point2D (px, py)
{
this.x = px;
this.y = py;
Point2D.prototype =
{
constructor: Point2D,
move:function (mx, my)
{
this.x = mx;
this.y = my;
},
translate:function (dx, dy)
{
this.x += dx;
this.y += dy;
}
};
};
I instantiate the object as follows:
var p2d1 = new Point2D(2,3);
Then I call one of the methods as follows:
p2d1.move(1,2);
And the result is:
TypeError: Object #<Point2D> has no method 'move'
I have not idea why my methods don't resolve.
I've messed around with it for a good while and found that I can declare Point2D methods this way and they will work.
Point2D.prototype.move = function () {};
Can anyone explain why they first style of replacing the entire prototype does not work, but adding functions to the existing prototype does work?
When you call new Point() the first time, Point.prototype is still an "empty" prototype. I.e. the instance that is created doesn't inherit any methods.
You change (replace) the prototype after the instance was already created. JavaScript has assign by value, not assign by reference. Quick example:
var a = 5;
var b = {c: a};
a = 10;
b.c is still 5, since assigning to a doesn't change what b.c refers to.
Point2D.prototype.move = function () {};
works because you are not replacing Point2D.prototype, you are simply mutating the existing object.
Overall, assignments to *.prototype should take place outside the constructor:
function Point2D (px, py) {
this.x = px;
this.y = py;
};
Point2D.prototype = { };
I am not sure, but defining the prototype inside the declaration of the "class" is unusual and to me, hard to define exactly how things would be resolved. When doing manual inheritence, I tend to follow more these patterns:
function Foo() {
this.bar = ...
}
Foo.prototype.baz = function() { ... }
OR
function Foo() { ... }
function Bar() { ... }
Foo.prototype = new Bar();
OR
Foo.prototype = {
blah: ...
}
Also I wouldn't usually create a "constructor" property manually, as this is a side effect of setting the prototype, but I know some popular libraries do this. In the middle example above, Foo.prototype.constructor == Bar.
If you really want to warp your brain create a second instance of Point2D and watch it have the move method available and working!
So here is what is happening.
define Point2D class
create instance of Point2D class
create initialization object
create execution context object per new keyword usage
attach prototype to execution context (at this point just Object)
run constructor method
assign value of x
assign value of y
assign new prototype value to Point2D class
what you want to do is to move the prototype setting out to the same scope as the class definition.

Categories

Resources