How do I add a method to an existing object? [duplicate] - javascript

This question already has answers here:
Javascript add method to object
(4 answers)
Closed 6 years ago.
var Person = function(name, age) {
this.name = name;
this.age = age;
};
//Now create three instances of Person with data you make up
var p1 = new Person('Aaron', 32);
var p2 = new Person('Casey', 30);
var p3 = new Person('Greg',31);
//Now add a sayName method on your Person class that will alert the name of whatever Person instance called it.
I'm not sure how to add a method to an existing class. I'm new to JavaScript. I understand how to add new properties but not new functions.

Add the method to the Person prototype chain.
Person.prototype.sysName = function() {
return console.log(this.name);
};

var Person = function(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.sayName = function () {
alert(this.name)
}
var p1 = new Person('Aaron', 32);
p1.sayName()
You can define Methods in using prototype
Person.prototype.myMethod = function() { ... }

Person.prototype.sayName = function() {
console.log(this.name)
}
you can add a prototype function to the Person class and then each person has access to the function.

One way to do this is by using prototyping you can add a method to an object though doing: myObject.prototype.myMethod = function(){ ... }
Person.prototype.sayName = function(){
console.log(this.name);
}
Another way can be directly adding it on the creation of Person, just note the method is duplicated for each instance in this case:
var Person = function(name, age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
}
};

Related

How do I apply methods from a constructor object to an arbitrary object [duplicate]

This question already has answers here:
Casting plain objects to class instances in javascript
(4 answers)
Closed 6 years ago.
I have a constructor object that has various fields; For a simple example, say
function Person(id, name) {
this.id = id;
this.name = name;
etc.
this.someFunction = function(xxx) {...}
}
Now, I have an arbitrary object with an id and name field
var somePerson = {id:123, name:"joe"}
I would like to inject the data from the somePerson instance into a Person constructor, so I can apply all of the methods from the Person class, but I am confused between apply, call, and bind.
I am aware that I can call a new constructor passing in all of the fields, but there are a lot of fields. Is there any easy way to just endow the somePerson instance with the methods from the Person class?
I think you got it wrong, what you are trying to do is :
var somePerson = new Person(123, 'joe');
then you will be able to write :
somePerson.someFunction();
You need to create a new Person instance, there's no need to use call or apply.
var somePerson = {id:123, name:"joe"};
var somePersonInstance = new Person(somePerson.id, somePerson.name);
somePersonInstance.someFunction(xxx);
You could have used call if the method was not inside the constructor, but on the prototype:
function Person(id, name) {
this.id = id;
this.name = name;
}
Person.prototype.someFunction = function(xxx) {…};
var somePerson = {id:123, name:"joe"};
Person.prototype.someFunction.call(somePerson, xxx);
You could use Object.assign() and assign properties of somePerson object to instance of Person
function Person(id, name) {
this.id = id;
this.name = name;
this.someFunction = function() {
return this.name;
}
}
var somePerson = {id:123, name:"joe"}
var p = Object.assign(new Person, somePerson)
console.log(p.someFunction())
Person is set up like a constructor function. You need to use the new keyword to instantiate a new copy of Person.
var joe = new Person(somePerson.id, somePerson.name);
Now joe will be an instance of Person.
joe instanceof Person //true
joe.id //123
joe.someFunction //function (xxx) {...}
Sure How's this;
function PersonFactory(id, name) {
return {
id: id,
name: name,
updateName: function(name) {
this.name = name
}
}
}
Some exmaples of it being used.
var somePerson = PersonFactory(1, "Luke")
var people = {
luke: PersonFactory(1, "Luke"),
will: PersonFactory(2, "Will"),
smith: PersonFactory(3, "Smith")
}
var persons = [
PersonFactory(1, "Luke"),
PersonFactory(1, "Will"),
PersonFactory(1, "Smith")
]
people.luke.updateName("Harry");

How to use object oriented without using keyword ('new')

What am I trying to do is as following:
var Person = function(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
// This will return error;
console.log(Person('John').getName());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
Am I misunderstanding something?
// This will return error;
console.log(Person('John').getName());
it returns an error bcoz Person() by default returns undefined ,but if you use new it will return the newly created object.
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
this works bcoz a new object with __proto__ set to Person.prototype is returned and since there is a getName() on it , it works as expected.
you may use scope safe constructor for your constructor to work without explicit new.
function Person(name) {
if(this instanceof Person) {
this.name = name;
} else {
return new Person(name);
}
}
http://www.mikepackdev.com/blog_posts/9-new-scope-safe-constructors-in-oo-javascript
If you don't want to have the new keyword all over your code (and I can't think of a good reason to want that, you would be basically hiding an important information), you could just do something like:
var pPerson = function(name) {
this.name = name;
};
pPerson.prototype.getName = function () {
return this.name;
};
var Person = function (name) {
return new pPerson(name);
};
You can use Object.create() if you don't want to use the new keyword. Here's an example from MDN:
// Animal properties and method encapsulation
var Animal = {
type: "Invertebrates", // Default value of properties
displayType : function(){ // Method which will display type of Animal
console.log(this.type);
}
}
// Create new animal type called animal1
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = "Fishes";
fish.displayType(); // Output:Fishes
If you really really hate your self, you can do this
var Person = function(name) {
var This = {};
This.name = name;
//See note
Object.setPrototypeOf(This, arguments.callee.prototype);
return This;
}
Person.prototype.getName = function () {
return this.name;
}
var p = Person('John');
console.log(p.getName());
Note
You absolutely have to read about this.
You can try creating prototype functions as a part of parent function itself.
var Person = function(name) {
this.name = name;
this.get_name = function() {
return this.name;
}
return this;
}
Person.prototype.getName = function() {
return this.name;
}
// This will return error;
console.log(Person('John').get_name());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());

Inherited class not getting its own methods in Javascript

function Mammal(name){
this.name = name;
}
Mammal.prototype.displayName = function(){
return this.name;
}
function Organism(name){
this.orgName = name;
}
Organism.prototype.print = function(){
return this.orgName;
}
Organism.prototype = new Mammal(); //Organism inherits Mammal
//Testing
var o = new Organism('Human');
o.print()
This comes as undefined. Why? this should show since it is a method of class Organism.
print() does not show up in the object
When you do:
Organism.prototype = new Mammal(); //Organism inherits Mammal
you replace the entire prototype object, thus wiping out the previously assigned:
Organism.prototype.print = function(){
return this.orgName;
}
You can fix it by changing the order so you "add" your new method to the inherited prototype:
function Organism(name){
this.orgName = name;
}
Organism.prototype = new Mammal(); //Organism inherits Mammal
Organism.prototype.print = function(){
return this.orgName;
}
FYI as an aside, you should be thinking about using Organism.prototype = Object.create(Mammal.prototype); instead and you should be calling the constructor of the base object too. See here on MDN for examples.
When you assign
Organism.prototype = new Mammal();
you are clobbering the Organism.prototype object that had the print function on it. Try this instead for your inheritance:
function Mammal(name){
this.name = name;
}
Mammal.prototype.displayName = function(){
return this.name;
}
function Organism(name){
this.orgName = name;
}
Organism.prototype = Object.create(Mammal.prototype);
Organism.constructor = Mammal;
// or _.extend(), if using underscore
jQuery.extend(Organism.prototype, {
print: function(){
return this.orgName;
}
});
//Testing
var o = new Organism('Human');
o.print()

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

Javascript - How to define a Constructor

I have an object written like this:
Object1.prototype = {
isInit: false,
Get : function (){}
}
Now I'd like to add a constructor which takes one parameter. How can I do it?
Class declaration
var User = function(name, age) { // constructor
}
User.prototype = {}
Instance variables (members)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {}
Static variables
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
staticVar: 15,
anotherStaticVar: 'text'
}
Here I defined two static variables. Each User instance has access to these two variables. Note, that we can initialize it with value;
Instance functions (methods)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
getName: function() {
return this.name;
},
setName: function(name) {
this.name = name;
}
}
Usage example:
var user = new User('Mike', 29);
user.setName('John');
alert(user.getName()); //should be 'John'
Static functions
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.create = function(name, age) {
return new User(name, age);
}
User.prototype = {}
Assuming that by "ctor" you mean "constructor", in JavaScript that's just a function. In this case your constructor would need to be "Object1" itself - in other words, what you've got there makes sense if you have already defined "Object1" to be a function.
Thus,
function Object1(param) {
// constructor code
}
would be the constructor for your type.
Now there are some JavaScript libraries that provide a utility layer for defining classes. With those, you generally pass some sort of object (like you've got) that includes an "init" function. The libraries provide APIs for creating "classes" and for extending one class from another.
Javascript has prototype based object model. Check this mozilla wiki page and suddenly you'll feel much better in js land.
We can define a constructor in javaScript is same as we fine function, so constructor is just a function.
//function declaration
function func(){}
In case of Contructor We use initial letter in caps in construct like
//constructor
function Func(){}
now do whatever you want to with your constructor
var constructor1 = new Func();
class CLASS_NAME
{
private:
int variable;
public:
CLASS_NAME() //constructor
{
variable = 0;
}
};

Categories