Use the variable name as part of your js value

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

Something like that:

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

So it will be

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

The context is not important, I know many longer ways to do the same, but it would be great to use the shortest.

+6
source share
2 answers

Mmm - the closest I can imagine is using 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> 
+2
source

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

What can be done the other way around: you can call a JS object with a name.

For instance:

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

Edit: Have you ever visited a library like Backbone or KnockoutJS? I'm not sure what you are doing, but I think that you are building the functionality that these libraries already provide ...

0
source

Source: https://habr.com/ru/post/957033/


All Articles