I am learning prototype in JavaScript and this is the code I am trying -
<script>
function employee(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var trialcoder = new employee('trialcoder', 26, 'M');
//employee.prototype.salary = null;
trialcoder.salary = 19000;
document.write("salary is "+ trialcoder.salary);
</script>
My thoughts- To add another property we need to use prototype like - employee.prototype.salary = null; so on un commenting this line, I was expecting an error but it was not..let me know where I am wrong in the prototype concept.
Code Source - http://www.w3schools.com/jsref/jsref_prototype_math.asp
Your code is correct, because when you called
var trialcoder = new employee('trialcoder', 26, 'M');
You got an object instance of employee and just like any other object you can add properties to your trialcoder object like
trialcoder.salary = 19000;
In this case, the salary property is only available to your trialcoder object and if you make another instance of employee like var another = new employee() you have no salary property in another object, but, if you do something like
function employee(name, age, sex) { //... }
employee.prototype.salary = 19000;
and then make instances like
var anEmp = new employee();
console.log(anEmp.salary); // 19000
Make another instance
var newEmp = new employee();
console.log(newEmp.salary); // 19000
if you want, you can
newEmp.salary = 10000;
console.log(anEmp.salary); // 10000
Which means, when you add a property in the prototype of a constructor (employee) then every object instance can share the same property and after making an instance from the constructor, you can change the property of an instance but this won't effect other instances. Hope it's clear enough now.
Your code is right and you will not receive error because using prototype your setting property salary of class employee and after creating an object of your class ur are setting the property for that specific object,if you create another object you can set its property salary too
If you set property using prototype then all objects of that class will share that (salary) property .
Related
I recently read that using private method is bad because they are very memory inefficient because a new copy of the method would be created for each instance. In the example given, how is dispalyIncreasedSalary more efficient than increaseSalary?
var Employee = function (name, company, salary) {
this.name = name || ""; //Public attribute default value is null
this.company = company || ""; //Public attribute default value is null
this.salary = salary || 5000; //Public attribute default value is null
// Private method
var increaseSalary = function () {
this.salary = this.salary + 1000;
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
};
};
// Create Employee class object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);
In the following example is this.dispalyIncreasedSalary reused for all objects?
No. You are binding it to this. So each gets it's own copy of that. That is what an instance member means. They bind to instance and not to Class/Object.
What about this.name etc. properties?
Same.
Aren't the this.propName not copied for all the instances?
If that happens all instance see the same value and that's a big NO.
You are correct that it is wasteful/inefficient to duplicate what could be a shared function for each instance.
You should investigate how JavaScript prototypes work: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
So shared methods would be placed onto every object and shared like this:
Employee.prototype.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
}
New to programming...I'm trying to learn about object inheritance in JavaScript.
I'm getting an error for the following code. It says:
TypeError: Cannot find function getName in object [object Object]
Does __proto__ (aka "dunder proto") not work in App Script? How can I set an inheritance to something other than the default "Object" without it?
function onPlay(){
//create an employee constructor
function Emp(last, first){
this.first = first;
this.last = last;
this.getName = function() {return(this.first+this.last);}
}
//create an employee
var emp1 = new Emp("Halpert", "Jim");
//log the employee's name
Logger.log(emp1.getName());
//create a manager constructor
function Mgr(){
this.salary = 100,000;
}
//managers are also employees
Mgr.__proto__ = Emp.prototype;
//create a manager
var mgr1 = new Mgr("Scott", "Michael");
//log the manager's name
Logger.log(mgr1.getName());
}
Rather than:
Mgr.__proto__ = Emp.prototype;
You probably want:
Mgr.prototype = Object.create(Emp);
The __proto__ property is for mutating prototypes, and isn't necessarily available in all JavaScript engines. To set a prototype for your custom object constructor, you want to set the prototype object on the constructor function to an instance of the base class (with Object.create not calling the parent constructor unnecessarily).
I am creating a map to which I am adding a custom class object,
var member_map = {};
var memberAction = new MemberActions(members.data[i].id, members.data[i].name);
member_map[memberAction.id] = memberAction;
Now when I try to get back a MemberActions object from the map using an ID, i get an Object rather than a MemberActions object.
var memberAction = member_map[fetch_id];
How do I cast the object?
EDIT:
My class defn:
class MemberActions {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
JS doesn't have such a thing as object casting.
When you say you've got an Object this may mean when you try to console.log(memberAction) you get told that it's an Object - however it doesn't mean that isn't a MemberActions object.
To check the name of it, try:
console.log(memberAction.constructor.name)
memberAction.constructor should also contain the constructor you've defined.
So I am designing a grade book interface and I have a course defined as:
<script>
course = new Object();
var name;
var gradingareas;
var finalgrade;
</script>
then later I want to create a new instance:
var gradingareas = new Array("Homework", "Classwork", "Exams");
course1 = new course("CS1500", gradingareas, 85);
I have also tried without the var in front to no avail. I get an "Uncaught TypeError: Object is not a function" I am very new to javascript so I don't even know if Im going about this the correct way. Any help is appreciated Thanks.
Your existing code:
// Creates a new, empty object, as a global
course = new Object();
// Creates three new variables in the global scope.
var name;
var gradingareas;
var finalgrade;
There is no connection between the variables and the object.
It looks like you want something more like:
function Course(name, gradingareas, finalgrade) {
this.name = name;
this.gradingareas = gradingareas;
this.finalgrade = finalgrade;
}
Then:
var course1 = new Course("CS1500", gradingareas, 85);
Note the use of a capital letter for naming the constructor function. This is a convention in the JS community.
JS is prototypical, rather than class based and if you are new to it there are advantages to learning this immediately rather than trying to mush classical inheritance models from it, however, classical inheritance is alive and well in JS.
Anyhow, to answer how you would access your variables:
course1.name works fine with the example above.
If you wanted to privatise your data you could take this approach using closure:
var Course = function(name, grade) {
// Private data
var private = {
name: name,
grade: grade
}
// Expose public API
return {
get: function( prop ) {
if ( private.hasOwnProperty( prop ) ) {
return private[ prop ];
}
}
}
};
Then instantiate a new object:
var course = new Course('Programming with JavaScript', 'A');
and start using all that private data:
course.get('name');
Of course, you'd probably want setters to manipulate that data too ;)
The code that you described does the following:
// Declares a memory variable called course and stores and object in it
var course = new Object();
// Declares three variables
var name;
var gradingareas;
var finalgrade;
These declared variables aren't automatically connected to the object. If you want these properties declared on the object you have 2 options:
Declare them as properties of the object
Declare them on the prototype of of the object
Example1: declare them as properties of the object:
// Declares a memory variable called course and stores and object in it
var course = new Object();
// Access or create new properties with . or [] operator
course.name = 'math';
course.gradingareas = 'muliple';
course['finalgrade'] = 'A'
console.log(course);
Example2: Declare them on the prototype:
// Create a constructor function
function Course (name, grade) {
this.name = name;
this.grade = grade;
}
// course is added on the prototype
Course.prototype.gradingareas = 'some gradingareas';
// the name and the grade are added on the object itself
var course = new Course ('willem', 10);
console.log(course);
To create a very simple object with constructor and default values, you can do :
//My object with constructor
var myObjectWithConstrutorFunction = {
//construtor function with default values in constructor
myConstrutor: function(Name = 'bob', Age = 18){
this.Name = name;
this.Age = age;
}
};
// instance
var myInstance = new myObjectWithConstrutorFunction.myConstrutor();
// show on console
console.log('object with constructor function: ', myInstance);
// show properties
console.log(myInstace.Name, myInstance.Age);
PS : It's a good practice create a constructor's name with the same name of the class, if you are creating a external class.
Is it okay to add properties to an object at runtime? It seems to run okay but are there any issues I should be aware of?
I'm using a 3rd party javascript API which has an object class, which I've instantiated and added my own property to after instantiation, like the code below:
For example can I do this:
var Car = function (id, type) {
this.id = id;
this.type = type;
};
var myCar = new Car(1,"Nissan");
// CAN I DO THIS: (needsWork not a property of object Car)
myCar.needsWork = true;
Actually, you have two ways to do that in JavaScript:
add a method or property to an instance (this car only)
var myCar = new Car(1,"Nissan");
myCar.needsWork = true;
add a method or property to the car prototype (all cars, even already existing ones)
var myCar = new Car(1, "Nissan");
var biggerCar = new Car(2, "Hummer");
Car.prototype.needsWork = true;
alert( myCar.needsWork && biggerCar.needsWork
? "We need work"
: "Something wrong here"
);
Reference:
Object.prototype
Yea, this is called object augmentation. It is a key feature in JavaScript.
Yes
There is nothing wrong with that.
See Object Augmentation here: http://www.crockford.com/javascript/inheritance.html