1

i want to do something like this,

function MyObject(args){
    keys=Object.getOwnPropertyNames(args)
    keys.forEach(function(key){
        this[key]=args[key]             
    })
}

after this i tried creating an object, but it's attributes were not set..

n=new MyObject({title:'x',age:19})
console.log(n.title)

OutPut:undefined!!

so can anyone tell me what im doing wrong...i even tried replaced this[key] with MyObject[key], but got same result..

2
  • 1
    Use an arrow function instead, else your this will refer to the wrong object Commented Aug 3, 2018 at 7:57
  • thanks, it worked,sir Commented Aug 3, 2018 at 7:59

1 Answer 1

4

In the forEach, the value of this is not the instance of MyObject that you are creating. You could use an arrow function, or you could store the this you want in the upper scope:

function MyObject(args){
    var self = this;
    keys=Object.getOwnPropertyNames(args)
    keys.forEach(function(key){
        self[key]=args[key]             
    })
}

n=new MyObject({title:'x',age:19})

console.dir(n)
console.log(n.title)

function MyObject(args){
    keys=Object.getOwnPropertyNames(args)
    keys.forEach((key) => {
        this[key]=args[key]             
    })
}

n=new MyObject({title:'x',age:19})

console.dir(n)
console.log(n.title)

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

1 Comment

maybe you should add an example with an arrow function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.