let's say I have code like this:
var object1 = {};
object1.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
in this case, what does 'this' stand for? object1 or class1? And whenever I want to define a class constructor inside an object, what is the best way to do it?
For class1, because you can't make an object of type object1.
However, if the code would be:
function object1() {
this.class1 = function() {
this.property1 = null;
this.property2 = 'ab';
}
}
You could have:
var obj = new object1();
obj.class1();
obj.property2; // => 'ab';
var cls = new obj.class1();
cls.property2; // => 'ab';
So it could depend on context.
If you call it like so:
object1.class1();
Then this will refer to object1.
Related
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?
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();
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)
Example code:
var someVar = {};
someVar.text = "some text";
var thisFunc = function(){
this.subfunc = function(){
}
}
How can I assign thisFunc to someVar? If I do someVar = new thisFunc(), someVar.text will be gone.
Thank you.
I think you want something like bellow:-
var someVar = {};
someVar.text = "some text";
var thisFunc = function(){
//do some
}
someVar.func = thisFunc;
It seems that an extend function would come in handy in your situation. It's a little helper function, that assigns properties of one object to another one (if you are using a third party library like Underscore, you might already have such a function available):
function extend(obj1, obj2) {
for (var key in obj2) {
if (Object.prototype.hasOwnProperty.call(obj2, key)) {
obj1[key] = obj2[key];
}
}
return obj1;
}
Then you can do:
var someVar = {};
someVar.text = "some text";
var thisFunc = function(){
this.subfunc = function(){
}
}
someVar = extend(thisFunc, someVar);
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);