6

Can I get variable name when setting its value in js?

Somthing like this:

var js = '<span id="'+ ::self.name +'"></span>';

So it would be

 js = '<span id="js"></span>';

Context is not important, I know lots of longer ways to do the same, but it could be great to use the shortest.

4
  • 2
    From this alone, no. If you could give some more context to it, there could be some alternatives given though. Commented Oct 30, 2013 at 12:21
  • While it may be interesting, I think it's not useful - or please show a use-case for this Commented Oct 30, 2013 at 12:25
  • You may use server-side rendering: var <% echo variable name %> = "<% echo variable name %>"; Commented Oct 30, 2013 at 12:27
  • Your question is not clear, can you please paste more real code from your project? Commented Oct 30, 2013 at 12:32

2 Answers 2

2

Mmm - the closest thing I can think of is creating via templates :

Example

    //using this small template js code
    if (!String.prototype.supplant) {
        String.prototype.supplant = function (o) {
            return this.replace(/{([^{}]*)}/g,
                function (a, b) {
                    var r = o[b];
                    return typeof r === 'string' || typeof r === 'number' ? r : a;
                }
            );
        };
    }



var spanTmpl=  '<span id="{id}"></span>';


var a= spanTmpl.supplant({id:"js"});
var b= spanTmpl.supplant({id:"bla"});


console.log(a); //<span id="js"></span> 
console.log(b);//<span id="bla"></span> 
Sign up to request clarification or add additional context in comments.

2 Comments

Actually I need this in creating lots of templates out of array. Create even more templates to create template is not a good solution.
As I said : " the closest thing I can think of is "..... what you're asking is called reflection which js does not support.
0

No, you need to define a property in your js-object - i.e a name-property.

What's possible is to do the converse thing: You can call a JS-object with the name.

For example:

var propName = "prop";
var prop = "value";
console.log(window[propName]) // => will output "value"

Edit: Have you ever looked in to a Library such as Backbone, or KnockoutJS? I'm not sure what you're doing, but my best guess is that you're building functionality those libraries are already providing...

1 Comment

Sure, I've worked with bb and knockout. Not the case.

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.