Is there a way to customize/override assignment operations in JavasScript?
Asked Answered
B

2

0

Every time I assign a string, I'd actually like to assign a string object, without the extra code.

This var foo = "bar";
becomes var foo = new String("bar");

Basically hi-jacking the assignment.


Follow-up:
If the above is not possible is there a way to prototype the string variable type, rather than the String object?

As pointed out by armando, the foo would be a string type, but is essentially a customized array. It would be nice to be able to prototype functions to that class.

Bend answered 22/9, 2010 at 14:51 Comment(9)
@vol7ron: based on the questions that you have been asking recently, I think that you really want to be programming in Ruby. JavaScript doesn't support the kind of metaprogramming that you seem to be after.Lapoint
@Adam Crossland: My questions lately have no real merit. It's been a while since I've done any intense JavaScript, so I'm just kind of getting back into it (I refuse to use Prototype or JQuery). If Ruby could be run as part of a client-side web application, I would look more into it, but my focus is still on ECMAScript. Server-side, I'm still a Perl devotee. :)Bend
@Adam Crossland: In your profile, your blog points to Google - intense :)Bend
I'm not sure why you'd want to do this. Every string literal in JS has the same access to String.prototype functions as a String object. "zomgwtf".toUpperCase() works fine.Convolvulaceous
This goes into a lot of detail about strings, literals and objects. Also, you might find this question informative.Kashgar
@MooGoo: I think the main reason I would like to know is for prototyping variables on-the-fly, see my question hereBend
@sje397: yes, that question/answer was very helpful! +1. So would adding a closure to the property list keep it in String object mode? Additionally, could you use a closure method to mimic a property value?Bend
I give the answer at another post: https://mcmap.net/q/1924366/-how-to-set-object-property-in-prototype-function-scope-problemCzarevitch
I give the answer at another post: https://mcmap.net/q/1924366/-how-to-set-object-property-in-prototype-function-scope-problemCzarevitch
M
2
  1. No this is not possible
  2. If it was possible, you really would not want to do this, at least not globally.

  • The string variable type does not have all the extra overhead that an object does.
    Note: the string array that is created (in your case, foo) would have other properties (eg foo.length)
  • Objects come at a performance hit
Mahan answered 22/9, 2010 at 14:52 Comment(1)
It is possible to override assignment to Proxy objects using handler.set().Rosalbarosalee
C
0

It's not quite what you're looking for, but you may want to look at Overriding assignment operator in JS

Cornish answered 11/8, 2014 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.