i am new to oop in javascript.
var obj1 = {
name : 'honda',
getName : function(){
console.log(this.name);
}
}
var obj2 = {name:'maruti'};
I want to access getName of obj1 with scope of obj2, like obj2.getName().
Is this what you want:
obj1.getName.call(obj2);
As @roland said, you can also use .apply(obj2, [arr of args]) if you want to provide an array of arguments to the method.
EDIT:
If you want to import all obj1 methods into obj2, you can do that with pure JavaScript:
for (var m in obj1) {
// if you want to copy obj1's attributes, remove this line
if (obj1[m] instanceof Function) {
obj[2][m] = obj1[m];
}
}
Or you can do it with jQuery:
$.extend(obj2, obj1);
obj2 simply makes no sense. You either get the name of obj2 in obj2's scope or the name of obj1 in the scope of obj1. The name of obj2 is "mauruti". That's what the answer is in the scope of obj2 unless you change the name of obj2 to be "honda".If are looking to use obj1 as a template for creating new objects, you can use Object.create to do this.
var obj1 = {
name : 'honda',
getName : function(){
console.log(this.name);
}
}
var obj2 = Object.create(obj1);
obj2.name = 'bob';
obj2.getName(); // outputs 'bob'