1

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

i want output to be honda using obj2 scope.
@user2087122 why would you want that?
how to inherit obj1 in obj2?
if you want honda, then what is obj2 even for?
@user2087122 - asking for the answer to be 'honda' in the scope of 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".
|
0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.