Function method in object in Javascript - javascript

I am working on a Javascript object exercise. My output is not what I expected. Please take a look at my code and give some advise. Here is the code:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models = brand;
};
}
var c = new myFunction ("pc");
c.add("HP");
c.add("DELL");
console.log(c.models);
The output is "DELL"
My expected output is ["HP","DELL"]
Thank you so much for your help!

Change the add function. You want to push the brand into the model. Not set the model to it.
this.add = function (brand){
this.models.push(brand);
};

To add something to an array, you should use the .push() method.
Change your code to:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models.push(brand);
};
}
P.S. It is customary to name such constructor type of functions starting with a capital letter.

Related

How to add a method to an array object that was made by a construction function

trying to solve the following problem.
I have a construction function like:
function Person (name){
this.firstName = name;
}
than I make some objects:
var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");
and finally attach them together:
var family = [myFather, myMother, myChild];
Now I would like to attach a method driver() to 'family', that will use the 'firstName' variable from the constructor function to choose, who is going to drive
Use another class Family and add a setDriver method to it:
function Person (name){
this.firstName = name
}
function Family (members){
this.members = members;
this.driver = members[0];
this.setDriver = function(name){
this.driver = this.members.filter(member => member.firstName == name)[0]
}
}
var myFather = new Person("John");
var myMother = new Person("Mary");
var myChild = new Person ("Sonny");
var family = new Family([myFather, myMother, myChild]);
console.log(family.driver)
family.setDriver("Sonny")
console.log(family.driver)
// At first you should remove comma from you Person function, and use semicolon(;)
// Just create function
function driver(firstName = this.firstName) {
console.log(`Drive is ${firstName}`)
}
driver.call(this, family[0].firstName)
// Result Drive is John
// or you can directly call driver function as method of any family object like
driver.call(family[0])
// Above code will produce same result, please try this

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();

Dynamically calling a property's method

Okay see the following code:
function person(name){
this.name = name;
this.say = function(){
alert(this.name);
}
};
Main = {};
Main.person1 = new person("p1");
Main.person2 = new person("p2");
Main.person3 = new person("p3");
executeSay = function(argument1){
//Implementation
}
What executeSay should do is, call the say method of the given argument, I am not sure how it goes but let me put this way executeSay("person1") should execute Main.person1.say() and so on. I think we can accomplish this by call method but I am not sure about the implementation.
Please don't suggest the following approach
say = function(){
alert(this.name);
}
say.call(Main.person1);
If you already pass the object in the function, you can access all its methods there, so use:
executeSay = function(person){
person.say();
}
and then call this function by, e.g.,
executeSay( Main.person1 );
I'd do it like this:
function Person(name){
this.name = name
}
Person.prototype.say = function () {alert(this.name)}
var main = {
person1: new Person('p1')
, person2: new Person('p2')
, person3: new Person('p3')
}
function executeSay(personStr) {main[personStr].say()}
(Updated to reflect the the string parameter for executeSay)
Let executeSay calls the say method on the argument object:
executeSay = function(person){
person.say();
}
Demo.
Is this not working?
executeSay = function(person){person.say()}

JavaScript - Meaning of: var DndUpload = function (inputElem){};

Can I kindly ask for explanation:
What does the code below represent? Does it create a DndUpload Ojbect? Or, does it create a DndUpload() function? What I miss is the statement new normally present during JavaScript objects creation. Can I kindly ask for some explanation, as I am confused.
var DndUpload = function (inputElem)
{
this.input = inputElem;
this.dropZone = null;
this.isDragging = false;
this.init();
};
As far as I know this is the way to create object in Javascript:
var myObject = new function()
{
};
If you have any link with explanation, that would help. Thank you.
It's a worse way of writing this:
function DndUpload(inputElem)
{
this.input = inputElem;
this.dropZone = null;
this.isDragging = false;
this.init();
}
which is a function declaration. It does not create an instance of DndUpload. Technically, it does create an object – its name is DndUpload and it is an instance of Function. To create an instance of this "class:"
var instance = new DndUpload(document.getElementById('someInputId'));
var myObject = new function()
{
};
Defines an anonymous constructor function and then instantiates a new object using the anonymous constructor function. It could have been replaced with var myObject = {}.
var DndUpload = function (inputElem)
{
this.input = inputElem;
this.dropZone = null;
this.isDragging = false;
this.init();
};
Defines a constructor function (technically an anonymous constructor function assigned to a variable). You can then create objects of this "class" by invoking the constructor function with new:
var dndUploadObject = new DnDUpload(),
anotherUploadObject = new DnDUpload(); //2 unique DnDUpload objects
the code you have essentially creates a constructor for a "class" it's more or less a blueprint for an object.
It then puts that constructor into a variable called DndUpload
So you can now make an object with
var myObject = new DndUpload(input elem)

JSON.stringify ignore some object members

Heres a simple example.
function Person() {
this.name = "Ted";
this.age = 5;
}
persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);
If I have an array of Person objects, and I want to stringify them. How can I return JSON with only the name variable.
The reason for this is, I have large objects with recursive references that are causing problems. And I want to remove the recursive variables and others from the stringify process.
Thanks for any help!
the easiest answer would be to specify the properties to stringify
JSON.stringify( persons, ["name"] )
another option would be to add a toJSON method to your objects
function Person(){
this.name = "Ted";
this.age = 5;
}
Person.prototype.toJSON = function(){ return this.name };
more: http://www.json.org/js.html
If you're only supporting ECMAScript 5 compatible environments, you could make the properties that should be excluded non-enumerable by setting them using Object.defineProperty()[docs] or Object.defineProperties()[docs].
function Person() {
this.name = "Ted";
Object.defineProperty( this, 'age', {
value:5,
writable:true,
configurable:true,
enumerable:false // this is the default value, so it could be excluded
});
}
var persons = [];
persons[0] = new Person();
persons[1] = new Person();
console.log(JSON.stringify(persons)); // [{"name":"Ted"},{"name":"Ted"}]
I would create a new array:
var personNames = $.map(persons,function(person){
return person.name;
});
var jsonStr = JSON.stringify(personNames);
see this post specify the field you'd like to include.
JSON.stringify(person,["name","Address", "Line1", "City"])
it is match better then what suggested above!

Categories

Resources