0
var s = {

    fname:'Ashish',

    lname:'Gokhale',

    getFullName: function(){
        return this.fname +' '+ this.lname;
    }

}

var p = {fname: "Xyz", lname: "Abc"};

Above are my two javascript object.

I want full name with p's variable without copying the data from any object.

I want this in a way that both object will retain there original value what they currently have. Is there any way to achieve this?

4
  • Not clear what you're asking. You want to extract data from p; then what's the relevance of s? Commented May 21, 2016 at 17:09
  • Your syntax is erroneous. getFullName(){ should be getFullName: function(){ Commented May 21, 2016 at 17:10
  • var s = { fname:'Ashish', lname:'Gokhale', getFullName:function(){ return this.fname +' '+ this.lname; } } var p = {fname: "Xyz", lname: "Abc"}; s.fname=p.fname; s.lname=p.lname; console.log(s.getFullName()); Commented May 21, 2016 at 17:14
  • Yes it should be in a way getFullName : function(){}, but what mainly I want is, I want to use getFullName for p varriable: it should return me Xyz Abc, without copying method from one varriable to other. Commented May 21, 2016 at 17:15

1 Answer 1

2

Use Object.assign() to merge the array, which updates the two properties.

var s = {
  fname: 'Ashish',
  lname: 'Gokhale',
  getFullName: function() {
    return this.fname + ' ' + this.lname;
  }
}
var p = {
  fname: "Xyz",
  lname: "Abc"
};

Object.assign(s, p);

console.log(s.getFullName());


UPDATE : In case if you don't want to update the original object then you can generate a new object with it by passing an empty object as first parameter.

var s = {
  fname: 'Ashish',
  lname: 'Gokhale',
  getFullName: function() {
    return this.fname + ' ' + this.lname;
  }
}
var p = {
  fname: "Xyz",
  lname: "Abc"
};

console.log(Object.assign({}, s, p).getFullName());

For older browser check polyfill option of the method.


Another option that you can use is bind() method, which helps to update the this keyword value, set p as this argument in bind().

var s = {
  fname: 'Ashish',
  lname: 'Gokhale',
  getFullName: function() {
    return this.fname + ' ' + this.lname;
  }
}
var p = {
  fname: "Xyz",
  lname: "Abc"
};

var fn = s.getFullName.bind(p);

console.log(fn());

Sign up to request clarification or add additional context in comments.

4 Comments

Now s has lose its definition, the case is this I have to retain definition of variables I can not assign it to temporary variable, It was an interview question in cognizant.
@Ashish : added last method using bind, which may help you
Thanks, it helped me a lot
@Ashish : glad to help you :)

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.