0

I have made a simple object

var myObject = {
formname: $('form'),
input: this.formname.find('input'),

init: function() {
    console.log(myObject.input)
}

}

myObject.init();

http://jsfiddle.net/t3fjffLg/

But this does not work. I want to use my name property in name2 property. What is the best approach for sharing properties ? Do I have to use prototype instead ?

Johansrk
  • 5,160
  • 3
  • 38
  • 37

2 Answers2

0
var myObject = {
    name: 'Johan',
    name2: function(){return this.name},

    init: function() {
        console.log(this.name2())
    }
}
Serhiy
  • 2,505
  • 3
  • 33
  • 49
  • it just seems a bit overkill to have a function, just to share a value. – Johansrk Nov 18 '15 at 12:50
  • @Johansrk I could be wrong but this seems like the easiest way to achieve what you asked. The alternative is as Hatem mentioned in terms of setting the property on initialization. What exactly are you trying to achieve? As name: "Johan", name2: this.name even if it worked seems like quite useless code. – Serhiy Nov 18 '15 at 12:55
  • It would just be nice to fx share a selector. See my edited code – Johansrk Nov 18 '15 at 12:58
  • @Johansrk Yeah, I would still simply wrap in a function and return. That would allow you to return the selector as you wish. I don't think it's an overkill as the alternatives are way messier. – Serhiy Nov 18 '15 at 13:11
0

Your goal is to initialize the "name2" with the same value of "name". So, the best approach to do that is to make it inside " init " method:

var myObject = {
    name: 'Johan',
    name2: null,

    init: function() {
        this.name2 = this.name
        console.log(myObject.name2)
    }
}

myObject.init();

Or if you insist to assign the value of the property in the header. Then you have to follow this approach :

name2: function(){ return this.name }
Hatem
  • 123
  • 11