Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable name as part of its value js

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.

like image 549
Prosto Trader Avatar asked Oct 30 '13 12:10

Prosto Trader


1 Answers

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> 
like image 145
Royi Namir Avatar answered Nov 15 '22 15:11

Royi Namir