Search code examples
javascriptjavascript-objects

how can i create an objects property from variables in javascript?


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


Solution

  • 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)