Reputation: 63
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()
.
Upvotes: 1
Views: 60
Reputation: 11352
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);
Upvotes: 1
Reputation: 44916
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'
Upvotes: 0