Why do I need prototype here? - javascript

can someone explain what's the difference between this:
<script>
function Employee() {
this.name = "serj";
}
function Manager() {
Employee.call(this);
this.dept = "general";
}
var jim = new Manager;
console.log(jim.name); //serj
</script>
And this:
<script>
function Employee() {
this.name = "serj";
}
Manager.prototype = Object.create(Employee.prototype);
function Manager() {
Employee.call(this);
this.dept = "general";
}
var jim = new Manager;
console.log(jim.name); //serj
</script>
So the question is why should I create a prototype?If manager calls employee and all works fine?

Calling the constructor function for Employee will run all the code that is inside that function. It won't perform all the side effects (i.e. creating a new object, assigning it to this and making it an instance of Employee … and you wouldn't want it to because you want it to be an instance of Manager).

Related

TypeError: ... is not a function

My JavaScript code in NodeJS results in:
TypeError: ninja.changeName is not a function
Following is my code:
function Ninja(name){
this.name = name;
var changeName = function(name2) {
this.name = name2;
}
}
var ninja = new Ninja("John");
ninja.changeName("Bob");
console.log(ninja.name);
What's wrong with the code?
var changeName will just create a reference to a function which will be lost once the function is done executing.
You must assign the function as a property of the Ninja function instead:
function Ninja(name) {
this.name = name;
this.changeName = function(name2) {
this.name = name2;
}
}
var ninja = new Ninja("John");
ninja.changeName("Bob");
console.log(ninja.name);
var changeName = function(name2) {
this.name = name2;
}
You are declaring a function but not attaching that to the object.
It should be
this.changeName = function(name2) {
this.name = name2;
}
So that the property changeName as a function attached to the object.
You are assigning a function to a variable. This isn't the same as setting a function in the objects prototypal inheritance structure and the variable changeName is only in scope within the context of Ninja.
You can assign the function to this.changeName (important that you're binding to this) like the following:
function Ninja(name){
this.name = name;
this.changeName = function(name2) {
this.name = name2;
}
}
Or you could use prototypes:
function Ninja(name){
this.name = name;
}
Ninja.prototype.changeName = function(name2) {
this.name = name2;
}
Although these approaches look fairly similar, the difference is very important. The first approach creates a new function for every Ninja created. The second approach will use the same function for each object. To look into the reason to use prototypal inheritance, there are various blog posts scattered around the internet.
You are declaring the changeName as a variable but not binding it with the 'Ninja', So I believe instead of using var, it should this. So the code becomes like this.
function Ninja(name){
this.name = name;
this.changeName = function(name2) {
this.name = name2;
}
}
Hope it helps.
function Ninja(name){
this.name = name;
return {
changeName : function(name2) {
this.name = name2;
}
}
}
In your code changeName is not exposed if you want to access the private data you can try with the above snippet
Another approach to make your function public available would be to first declare it private (Some prefer to use an underscore, like usual in .Net):
function Ninja(name) {
this._name = name;
var _changeName = function(name) {
this._name = name;
}
}
And then export it using return. Some might know this from the classical Java boilerplate Getters and Setters, where fields are declared private by default and Methods make them available:
function Ninja(name) {
this._name = name;
var _changeName = function (name) {
this._name = name;
}
return {
changeName: _changeName,
getName: function () {return _name;}
}
}
...And now, use the object:
var ninja = new Ninja("John");
ninja.changeName("Bob");
console.log(ninja.getName());

Javascript prototype method "Cannot set property"

I'm always getting Cannot set property 'saySomething' of undefined but why?
Am I making a mistake somewhere?
var Person = new Object();
Person.prototype.saySomething = function ()
{
console.log("hello");
};
Person.saySomething();
Debugging tip: You get this ..of undefined errors when you try to access some property of undefined.
When you do new Object(), it creates a new empty object which doesn't have a prototype property.
I am not sure what exactly are we trying to achieve here but you can access prototype of function and use it.
var Person = function() {};
Person.prototype.saySomething = function() {
console.log("hello");
};
var aperson = new Person();
aperson.saySomething();
The prototype property exists on functions, not on instantiated objects.
var Person = new Object();
console.log(Person.prototype); // undefined
var Person2 = function () {}
console.log(Person2.prototype); // {}
This is useful because things put on the prototype of a function will be shared by all object instances created with that function (by using new).
var Person = function() {};
Person.prototype.saySomething = function() {
console.log("hello");
};
console.log(
new Person().saySomething === Person.prototype.saySomething // true. they are the same function
);
If all you want is to add a method to the person object, there's no need for a prototype:
var Person = {};
Person.saySomething = function() {
console.log("hello");
};
Person.saySomething();
You can even use object literal syntax:
var Person = {
saySomething: function() {
console.log("hello");
}
};
Person.saySomething();
i was trying out some code thought of posting it, might help others.
<script>
var MODULE = {};
MODULE = (function (my) {
my.anotherMethod = function () {
console.log("hello ");
};
my.newMethod = function(){
console.log("hi new method ");
}
return my;
}(MODULE));
MODULE.anotherMethod();
MODULE.newMethod();
</script>
And please not var MODULE ={}, if this is not initialized with {} then it give cannot set property.
I know i am late to the party but as you see there is no satisfying answer available to the question so i am providing my own.
In your case when you write
var Person = new Object();
you are creating an instance of Object type.
You can add a property using prototype property to the Object, not to the instance of Object.which you can use by the instance laterly.
so you can define like
Object.prototype.saySomething = function ()
{
console.log("hello");
};
now you can call it like this.
Person.saySomething();
You can check here.
var Person = function(name) {
this.canTalk = true;
this.name = name;
};
Person.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name);
}
};
bob = new Person('bob');
bob.greet();

Can i create an object trough parent in js

I am new to OOJS and I'm a little confused trying to understand inheritance, I created two simple classes, person and student that inherit from person, is there an option to create student by passing data in the parent's constructor? if it's possible, how to do it ? can a child get all the properties and methods from the parent or only the methods?
**the fname and lName in the alert are undefined
function Person(fNme, lName) {
this.fname = fNme;
this.lName = lName;
}
Object.prototype.go = function() {
alert("I am going now last time you see "+ this.lName);
}
function Student() {
this.study = function () {
alert("I am studing !");
}
}
Student.prototype = new Person();
var s1 = new Student("sam", "bubu");
alert(s1.fname +"+"+ s1.lName)
you can use constructor stealing.
function Student(fName,lName) {
Person.call(this,fName,lName);
this.study = function () {
alert("I am studing !");
}
}
when you call Student constructor you can pass along arguments to Person() with call() to initialize variables in Person
This is done by just calling the parent constructor
function Student(fName, lName, whateverelse) {
Person.call( this, fName, lName ); // call base class constructor function
this.study = function () {
alert("I am studing !");
}
}

How to invoke function inside another function in JavaScript as I've mentioned below

I've a code
function person() {
name = "David";
hello = function() {
console.log("I'm in hello");
};
}
And I want to invoke hello function from outside. How can I achieve it?
Assign hello (and name) to this in person:
function Person() {
this.name = "David";
this.hello = function() {
console.log("I'm in hello");
};
};
Then, you can access the function like this:
var p = new Person();
p.hello();
this assigns the variables to the Person. This prevents the variables from polluting the global scope.
You could also pass parameters to Person:
function Person(name) {
this.name = name;
this.hello = function() {
alert("Hello! I'm " + this.name + '!');
};
};
var p = new Person("Fred");
p.hello();
function person() {
this.name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var personObj = new person();
personObj.hello ();
What you can do is that:
function person() {
name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var johnny = new person();
johnny.hello();
See this nice article: http://www.phpied.com/3-ways-to-define-a-javascript-class/
function person() {
name = "David";
this.hello = function() {
console.log("I'm in hello");
};
}
var p = new person();
p.hello();
or
function person() {
var obj={};
obj.name = "David";
obj.hello = function() {
console.log("I'm in hello");
};
return obj;
}
var p = person();
p.hello();
This is for your curiosity and clarity :)
You have declared global variables inside a function. Untill you execute the function the global variables will not come into existence and would not be accessible. Once you call the function the globals would be defined and initialized properly and thereafter you can call them from any scope in the javascript.
function person() {
name = "David";
hello = function() {
console.log("I'm in hello");
};
}
Now, in order to call hello from outside without using this or class pattern, you will have to first make a call (method execution) to person method. see this:
either person(); or console.log(person()); but not console.log(person);
and then you can easily call hello();
NOTE: This is for David's understanding purpose. Please do not use
arbitrarily global variables in your javascript.

Unable to get property of undefined or null reference

I am getting following error
Unable to get property 'showMsg' of undefined or null reference
on the last line of below code:
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
Actually I should be able to access showMsg() from Person instance since I have added it to the Function.prototype. Then why I am getting this error?
Well You Understand it all Wrong
Function.prototype.showMsg = function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
var personObj = new Person();
personObj.prototype.showMsg();
First you prototyped the function class, then create a custom class called Person, then you create an instance of Person. And then you are calling the very blue print which is showMsg which is 2 Mistakes 1 showMsg is not Bounded into the Person and then to call it if its bounded you call it directly like this
personObj.showMsg()
Will To Make This Script Work from my point of View if i got you write
write it like this ->
function Person() {
this.name = "Mahesh";
};
Person.prototype.showMsg = function () {
alert("This is a sample message.");
};
var personObj = new Person();
personObj.showMsg();
my script bound the showMsg Directly to the Person Class if you need it through the Person Object and Through The Function Class To Then you have to inherit from Function Class Like This
Function.prototype.showMsg=function () {
alert("This is a sample message.");
};
function Person() {
this.name = "Mahesh";
};
Person.prototype = Function;
Person.prototype.constructor = Person;
var personObj = new Person();
personObj.showMsg();
Regards

Categories

Resources