javascript prototype method not getting result - javascript

var Person = function(name,age,job){
this.name = name;
this.age = age;
this.job = job;
}
var dependar = new Person('Dependar',20,'Student');
now that we have created our constructor and all.
I'm trying to use prototype .
Person.prototype.city = 'Delhi';
we have attached new var city to the constructor and all the elements created with it(var dependar)
dependar.city is working properly, it is assigned to 'Delhi'
but when I try to attach a method using prototype
Person.prototype.dob = function(){
this.dob = 2017 - this.age;
}
but when I enter
dependar.dob;
it is displaying the function not the result
function (){
this.dob = 2017 - this.age;
}
What is going wrong? please help

when I enter dependar.dob;it is displaying the function not the result.
REASON:
This is because you have defined it as:
Person.prototype.dob = function(){
this.dob = 2017 - this.age;
}
which is assigning (2017 - this.age) to this.dob .But dob is not defined in the function.
What you can do:
Return value dob directly.
var Person = function(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
var dependar = new Person('Dependar', 20, 'Student');
Person.prototype.dob = function() {
return (2017 - this.age);
}
console.log(dependar.dob());

In the console, if you type dependar.dob, or if you use a console.log(dependar.dob), you are getting what you asked for -- the value of dob, which is a FUNCTION and so it does its best to display the contents of that value - the function source code.
To get the function value you need to execute the function, which means dependar.dob() -- note the use of the parens. Those cause the function to execute.

Related

How does "this" keyword work in the particular way?

I'm trying to learn JavaScript, but got stuck with a problem (more with misunderstanding "this" keyword) that doesn't give me move on.
I've watched a lot of content about it and barely understood it, but still have some troubles.
I have some code:
function Person (name, age) {
this.name = name;
this.age = age;
this.changeName = function (name) {
this.name = name;
}
}
What do we use "this" here for?
As I understood we use "this" to create variable inside function constructor and give it value of our "name" parameter that we could refer to it. Am I right?
Then I have this code:
var p1 = new Person ("John", 30);
p1.changeName ("Jane");
console.log(p1.name);
As I sorted out here, we call method that overwrites our variable that we created to refer to. But it doesn't change actual parameter. So if it's right why do we use it? Doesn't it matter to have actual "name" parameter changed?
The whole code is from teaching app!
So if it's right why do we use it? Doesn't it matter to have actual "name" parameter changed?
No, there's no need to do that in this example. changeName changes the property on the object that was created by new Person.
It's true that that example code is a bit odd, because it creates the changeName function in the constructor but doesn't do the kinds of things you'd normally do when you create the function in the constructor. I'd expect that code to either be this, which puts the changeName on the prototype:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.changeName = function(name) {
this.name = name;
};
(or the class equivalent) or this:
function Person(name, age) {
this.getName = function() {
return name;
};
this.changeName = function(newName) {
name = newName;
};
this.getAge = function() {
return age;
};
}
That code does update the parameter (which has no effect at all on the code calling Person). It doesn't create name and age properties at all; instead, it just makes their values accessible via getName and getAge. There's also a function to change name (changeName); but there's no function to change age. People write code like that so that age cannot be changed from outside code created within the Person constructor.
I guess you may misunderstand which parameter you actually change, so I rewrite it like so, holp this helps.
function Person (argument_name, argument_age) {
this.name = argument_name;
this.age = argument_age;
this.changeName = function (argument_change_name) {
this.name = argument_change_name;
}
}
let p1 = new Person ("John", 30);
p1.changeName ("Jane");
console.log(p1);
The this keyword is used to create and assign values to variables in the class. It is again used to create functions, either getters or setters. So in your code this.changeName is a function that when passed a value will change the name of the person.
eg.
var a = 5; // a is an integer
var b = "Han"; //b is a string
var c = function(name){
//code here
} // then c is also a function;

New Object Creation issues

Ok so the following function acts as a constructor to create an Employee object(no problem with that). But when I use this function to create 3 new employees I am messing up somewhere.
I know I'm supposed to set the properties and print the employee's name and phone number, but I am missing something or something is in the wrong place.
Thanks in advance for your help.
function Employe() {
var = name;
var = phone;
this.getName = function () {
return this.name;
}
this.setName = function (name, phone) {
this.name = name;
this.phone = phone;
};
}
var emp1 = newEmployee;
this.Name = 'jo';
this.Phone = ' 555-5551'
document.write(Employee.name Employee.phone);
var emp2 = newEmployee;
this.Name = 'jim';
this.Phone = '555-5552';
document.write(Employee.name Employee.phone);
var emp3 = newEmployee;
this.Name = 'jon';
this.Phone = '555-5553';
document.write(Employee.name Employee.phone);
In the following:
> var emp1 = newEmployee;
The variable on the left will be assigned the result of evaluating the expression on the right. There is no identifier newEmployee, so you will get an error. What you probably meant to write is:
var emp1 = new Employee();
That will call the constructor, which will return a new instance, a reference to which will be assigned to emp1.
Then you have:
> this.Name = 'jo';
The value of this is set when entering an execution context. For global code, it always references the global object (which is equivalent to window in a browser). So the above line creates a Name property of the global object and assigns the value 'jo';
What you wanted is probably:
emp1.setName('jo','555-5551');
The name of that method seems inappropriate given that it sets both the name and phone number.
> document.write(Employee.name Employee.phone);
Since you added the properties to the instance (emp1), likely that's the properties you want to read:
document.write(emp1.name + ' ' + emp1.phone);
or to use the getName method:
document.write(emp1.getName() + ' ' + emp1.phone);
and so on.
There's a lot wrong with your code example. The constructor is misspelled. The employee instances should be created like:
var emp1 = new Employee();
The instance properties should be set like:
emp1.setName('John');
You've also combined two setters into one, which is confusing.
To access the instance properties, you should use:
emp1.getName();
Not:
Employee.Name
Yes you have a lot of errors I think this is basically what you want to achieve.
function Employee(){
this.name;
this.phone;
this.getName = function(){
return this.name;
};
this.setName = function(name, phone){
this.name = name;
this.phone = phone;
};
}
function employ(){
var emp1 = new Employee();
emp1.name = 'jo';
emp1.phone = ' 555-5551' ;
alert(emp1.getName());
}
http://jsfiddle.net/umNTs/

Confusing Javascript prototype behavior

I have the following Javascript code;
var Person = function(name, age) {
this.name = name;
this.age = age;
return this;
};
Person.prototype.getAge = function() {
alert("Age : " + this.age);
}
var p1 = new Person("xyz",10);
p1.getAge();
This works perfectly and I get the alert as Age : 10
Now if I update the code as below (defined getAge() after instantiating Person object p1);
var Person = function(name, age) {
this.name = name;
this.age = age;
return this;
};
var p1 = new Person("xyz",10);
Person.prototype.getAge = function() {
alert("Age : " + this.age);
}
p1.getAge();
It still returns me the output as "Age : 10"
Now my question is how does this work correctly, since Person.prototype.getAge was defined after we have instantiated Person object p1 ?
Is it because of the way "prototype" works ?
Objects in javascript have a sort of a chain where if you ask them for a property, they will return theirs and if they don't have it, it'll try to find it above its chain, in your case, when p1 is asked for its getAge property, it looks for it in Person.prototype.
var Person = function(name, age) {
this.name = name;
this.age = age;
return this;
};
var p1 = new Person("xyz", 10);
var p2 = new Person("abc", 12);
Person.prototype.getAge = function() {
alert("Age : " + this.age);
}
p1.getAge = function() {
alert("I am " + this.age + " years old.");
}
p1.getAge(); // I am 10 years old.
p2.getAge(); // Age : 12
In this example, p1 has its own getAge property, so when asked, it returns it. On the other hand, p2 doesnt really have this property but can access it via "that chain" and returns the property of its prototype.
Yes that is the way prototype works. You can use this technique to extend strings, objects and arrays too.
Any object prototype can be modified at any time. Think about the libraries/frameworks that modify the base Object prototype...even the built in objects (Date, String, etc) will all have the modifications done to Object.prototype whether or not they happen immediately at page load
try this:
Object.prototype.myTest = function() { console.log('hi'); }
var a = new Date()
a.myTest(); //hi

Differences between javascript constructor functions

What is the difference between this...
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
and this...
function Person(name) {
this.name = name;
this.age = age;
this.sex = sex;
}
and this...
function Person() {
this.name = name;
this.age = age;
this.sex = sex;
}
Thanks!
David, I have a piece of code for a game I am building that looks like this...
function Player(node){
this.node = node;
this.grace = false;
this.replay = 3;
this.shield = 3;
this.respawnTime = -1;
...
return true;
}
and it does not return a reference error. Its an object for a player in a javascript game I am building...
As Brett said, the second and third constructor function will assign any global variable to the properties of the new Person instance. However, you can still use any argument that might be passed to the constructor:
function Person()//no args
{
//depending on which value is available:
//prop = n-th argument OR global variable OR undefined
this.name = arguments[0] || window.name || undefined;
this.age = arguments[1] || window.age || undefined;
this.sex = arguments[2] || window.sex || undefined;
}
var parrot = new Person('polly',1,'M');
console.log(parrot.name);//polly
var noSex = new Person('Joe',99);//if no global sex is set:
console.log(noSex.sex);//undefined
var sex = 'F';
var jane = new Person('Jane',25);
console.log(jane.sex);//F
The first relies on local variables set through parameters to set its instance variables/properties, the third relies on globals to set its properties, and the second is a mix.
1st one is valid, you initite your local variables with the parameters sent in the constructor. the rest doesnt really make sense.
in the 2nd one you kind of mixing parameters with some other variables which you can access at that point, you initate only the name using a parameter.
and the 3rd one is based on accessable variables, but none of them is given as a parameter, i never saw something usefull using 2nd and 3rd options..

Javascript : difference two ways declare variable in a function

I want to create an object. And, in almost code I have read, they often use this style:
function student(_id, _name, _year){
this.id = _id;
this.name = _name;
this.year = _year;
}
But, I don't know what the difference with below code :
function student (_id, _name, _year){
var id = _id;
var name = _name;
var year = _year;
}
I have tested for example, alert properties to screen, and see no difference.
Thanks :)
When you declare variables using var they are only visible in the scope of your function/constructor. They are private so to say.
Using this, in this case, goes hand in hand with a constructor function. When you instantiate a student all the values assigned to this will be publicly accessible.
First I recommend renaming your student into Student with a capital S. This is a convention that indicates it is a constructor and you need to use the new keyword.
function Student(id, name, year){
this.id = id;
this.name = name;
this.year = year;
}
If you now instantiate the Student you can access the values...
var student = new Student(1, "Name", 2012);
console.log(student.year); // => 2012
When using var you can't...
function Student (id, name, year){
var id = id;
var name = name;
var year = year;
}
var student = new Student(1, "Name", 2012);
console.log(student.year); // => undefined
function student(_id, _name, _year){
this.id = _id;
this.name = _name;
this.year = _year;
}
var s1 = new student(1, 'mike', 20);
console.log(s1.name); // give you mike
function student(_id, _name, _year){
var id = _id;
var name = _name;
var year = _year;
}
var s1 = new student(1, 'mike', 20);
console.log(s1.name); // give you undefined
Its about the scope of the variables.
In your first example, you are assigning id, name, and year as externally accessible properties for student. For example:
student.id, student.name, student.year
However, in the second example, those variables only have scope inside the student function. You cannot access their values from the outside.
the difference is the properties are public in the first while privat in the second.
there is no difference of leading var with or without underscore. the second example missmatching the arguments. id vs _id.

Categories