How to change property of the object by event? - javascript

I have a constructor:
var Constructor = function(property) {
this.property = property;
this.changeProperty = function() {
*by clicking should change the property*
}
}
Then I create an object:
var newObject = new Constructor(propertyValue);
newObject.changeProperty();
So, is it possible to change the property value of the already created object?

So, is it possible to change the property value of the already created
object?
Yes, try
var Constructor = function(property) {
this.property = property;
var self = this;
this.changeProperty = function( newProperty ) {
self.property = newProperty;
}
}
And invoke it as
var newObject = new Constructor(propertyValue);
newObject.changeProperty(newPropertyValue);

var Constructor = function(property) {
this.property = property;
this.changeProperty = function(newProp) {
this.property = newProp
}
}
var newObject = new Constructor("oldProp");
newObject.property //oldPropery
newObject.property = "newproperty"
newObject.property//"newproperty"
You can also do it using getter and setter.The property is already public.

Related

Copy object functions and properties in new object by value not by reference - javascript

I want to copy the functions and properties of an object into new object. The old object should not effect by changing made in new Object.
Here is the object definition:
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
I can access function1 using callobj.function1().
What I have tried to copy it:
Javascript:
var newcallobj = Object.assign({}, callobj);
In this case, i am not able to access function1 but i can access number property directly.
JQUERY:
var newObj = jQuery.extend(true, {}, callobj); OR
var newObj = jQuery.extend({}, callobj);
In this case, i am able to access function1 and property but when i change number like that newObj.number="222". It also change the value of original object.
I know that there is couple of other posts. But all is not working for me. Please let me know if i am doing any thing wrong?
AFTER #gurvinder372 answer(I am updating question):
After #gurvinder372 answer. It is working for first level of property but if it has another object like i show below and i change the value of property of another object. Then it is effecting on original object also.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Output of both is 123. #gurvinder372. can you check th above code ?
Object.assign only copies the enumerable properties of an object.
Use Object.create instead of Object.assign
var newcallobj = Object.create(callobj);
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
console.log(newcallobj.function1());
Ok. By the help of #gurvinder372. The following solution is working for me.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj = Object.create(callobj.anotherobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Please let me know if there is any better solution other than 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();

Accessing object properties in listener method

Let's say I have the following code:
var Obj = function() {
this.property = 1;
this.arr = [...] // array containing elements we want to add event listeners to
for (...) {
this.arr[i].addEventListener("click", this.listener, false);
}
}
Obj.prototype.listener = function() {
console.log( this.property ); // DOES NOT WORK! *this* does not point to Obj.
}
var a = new Obj();
How do I access object properties (and methods) within a listener? I would assume I'd need to pass it as a parameter? Is the way I'm going about this structurally wrong?
When the function is called as an event listener, the context (this) is changed to something other that the object itself.
To resolve this, manually bind the context to the object instance in the constructor using bind(). This way, this will always point to the object instance, independent of the calling context:
var Obj = function() {
this.property = 'foo';
this.listener = this.listener.bind(this);
}
Obj.prototype.listener = function() {
console.log(this.property);
}
var a = new Obj();
a.listener.call({});
As suggested by #Tushar, you can use Function.prototype.bind() and pass this.property as parameter
<body>
click
<script>
var Obj = function() {
var obj = this;
this.property = 1;
this.arr = [document.body];
for (var i = 0; i < obj.arr.length; i++) {
obj.arr[i].addEventListener("click"
, obj.listener.bind(obj.arr[i], obj.property), false);
}
}
// note order of parameters; e.g., `prop`, `e`
Obj.prototype.listener = function(prop, e) {
console.log(prop, e); // `1`, `event` object
}
var a = new Obj();
</script>
</body>

Adding methods to an JavaScript object

I could create an object with some methods, and later add a property to it as follows:
var myObj = (function () {
var my = {};
my.method1=function(){}
my.method2=function(){}
my.method3=function(){}
return my;
}());
myObj.myProperty=123;
How could I create the object first and add a property, and then later add the methods afterwards?
myObj={};
myObj.myProperty=123;
//How do I add the above methods to myObj?
I guess there are two solutions:
Merge the objects:
var myObj = {...};
// ...
var objWithMethods = (function() { ... }());
Object.assign(myObj, objWithMethods);
(Object.assign is an ES6 methods. A polyfill can be found in the link, libraries often also provide a method with similar behavior).
Pass the object the methods should be assigned to as argument:
var myObj = {};
myObj = (function (obj) {
var my = obj || {};
my.method1=function(){}
my.method2=function(){}
my.method3=function(){}
return my;
}(myObj));
You can do an extend operation using an existing object
var myObj = {...}
var myAdditionalMethods = { someMethod : function(){ } }
//extend the object
for(var i in myAdditionalMethods)
if(!myObj.hasOwnProperty(i))
myObj[i] = myAdditionalMethods[i];
there are a lot of libraries that have this functionality built in, but that is how you would do it without one
Even prototype can add the functions to original object.
var myObj = function() {
this.myProperty = 123;
}
myObj.prototype.method1 = function method1() {
alert("method1")
}
myObj.prototype.method2 = function method2() {
alert("method2")
}
var newObj = new myObj();
newObj.method1();
newObj.method2();
console.log(newObj)

Array with all Instances of Objects created with the same function constructor in Javascript

In trying to built a object with a inner propriety in the constructor function that keeps the array with all the objects created with the same constructor.
I'm thinking that the best way would be with a closure on object initialization and this is how I try to solve this:
function myObject (name){
this.name=name;
this.allInstances = [];
}
myObject.ptototype = {
init : function(){
return function(){this.allInstances.push(this.name)};
}(),
}
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.allInstances); // should print ["object1", "object2"]
Does anyone know how to achieve that ? Is that even possible ?
I'm specifically trying to get a solution which uses only function constructor and prototype to achieve that.
I know how to solve that by pushing the proprieties to an external array, like:
var allInstances = [];
function myObject (name){
this.name=name;
allInstances.push(this.name);
}
console.log(allInstances)
Place the Array as a property on the prototype, and it will be shared among all instances:
function myObject(name) {
this.name = name;
this.allInstances.push( this.name );
}
myObject.prototype.allInstances = [];
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.allInstances); // ["object1", "object2"]
Or if you want the Array to be more protected, use a module pattern, and include a function on the prototype to return the Array.
var myObject = (function() {
var allInstances = [];
function func(name) {
this.name = name;
allInstances.push( this.name );
}
func.prototype.getAllInstances = function() { return allInstances; };
return func;
})();
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(object1.getAllInstances()); // ["object1", "object2"]
You can put your array as a static member of myObject:
function myObject (name) {
this.name=name;
this.init();
}
myObject.allInstances = [];
myObject.prototype = {
init: function() {
myObject.allInstances.push(this.name);
}
};
I don't see where you are calling init(). I added a call to init() in the constructor.
It seems to me this would be easily done like so:
var MyType = function(name)
{
this.name = name;
MyType.Instances.push(this.name);
};
MyType.Instances = [];
MyType.prototype.getInstances = function()
{
return MyType.Instances;
};
var obj = new MyType('Hello');
var obj2 = new MyType('hello 2');
console.log(obj2.getInstances());
Would this do?
function myObject(name) {
this.name = name;
this.constructor.allInstances.push(this.name);
}
myObject.allInstances = [];
object1 = new myObject("object1");
object2 = new myObject("object2");
console.log(myObject.allInstances);

Categories

Resources