views:

60

answers:

2

Hey all,

So I know javascript pretty well, but I'm not sure about this one.

Tough to explain so I'll just show it:

var view = new View();

view.rating = 4.5;

Is there anyway to have view.rating be called as a function to manipulate the DOM a bit and set that rating to five?

So in View:

View.prototype = {

  rating : function() {
     $('div.stars').width(4.5);
  }

}

I know there are workarounds, using something other than "view.rating = 5". I'm not interested in those. I'm wondering if there is a way to set this up maintaining view.rating = 5. This is coming JS is coming straight from PHP essentially and I don't want to bog the PHP down with anonymous functions.. like view.rating = function() {...};

Thanks! Matt Mueller

+4  A: 

No. (Edit: not on all implementations of common browsers at least)

There isn't anything in Javascript equivalent to "overloading the = operator".

Edit:

I'm not sure if this is clear to you. If you make rating a function (either via the prototype or not), you should call it like view.rating(5), and it can update the DOM (or do anything).

Sinan Taifour
Or property setters.
Chetan Sastry
Yup. I'm just running into some serious constraints trying to make a custom Smarty template function and want to keep the strain on the server down as well. PHP has all these wild ways of doing things, I was wondering if Javascript had some little trick too. Thanks!
Matt
+3  A: 

Most implementations of JavaScript don't support creating getter/setter properties so it wouldn't be super useful on the web. However there are some implementations that do. Here's an example in Mozilla's implementation:

EDIT: Let me just clarify, writing getters/setters is syntactic sugar over the use of a getFoo()/setFoo(foo) style property. It is for the developer's benefit. IMO, for a web app (due primarily to IE's lack of support) it isn't quite realistic just yet. While IE market share is dropping, depending upon your demographics in a widely public app, a lot of your visitors at this point still won't have support for them.

Some more links of interest for you:

McKAMEY
+1: Nice ~!
Sinan Taifour
Learn something new every day! Thanks!
Matt
All JS implementations support getters and setters with the exception of IE's engine
olliej
@olliej: IE8 supports getters and setters for DOM objects, but only using the new ECMAScript 3.1 syntax, which other browsers don't (yet) support. http://msdn.microsoft.com/en-us/library/dd229916(VS.85,loband).aspx
outis