- Home /
Can I declare properties in JS?
In C#, I can declare properties like so:
public int Health
{
get { return _health; }
protected set { _health = value; }
}
- Does JS also support properties?
- If so, how can I declare them?
I already know I can just have Get/Set functions but that is not what I am after.
Answer by Mike 3 · Mar 12, 2011 at 08:36 PM
Yes, but you have to do it in explicitly declared classes
class Test extends MonoBehaviour
{
var moo = 1;
function get Moo() : int { return moo; }
function set Moo(value : int) { moo = value; }
}
That is then accessible the same way as c# properties ( blah.Moo )
If you try it with implicit classes you'll get some fantastically odd errors
Another caveat - you can't do static properties
Why does each of these produce: It is not possible to invoke an expression of type 'float'.
var a : Foo; function Start() { print(a.bar()); a.bar(12.3); }
@efreet: This code above will create a property and can't be used like functions. You have to use the property this way:
class Test extends $$anonymous$$onoBehaviour
{
var moo = 1;
function get $$anonymous$$oo() : int { return moo; }
function set $$anonymous$$oo(value : int) { moo = value; }
}
// Somewhere else
var a : Test; // assigned in the inspector or elsewhere
// Use it this way:
a.$$anonymous$$oo = 10; // this will call the set method
print("$$anonymous$$oo is: " + a.$$anonymous$$oo); // this will call the get method
If you actually want real functions, don't use the get and set keywords.
Your answer
Follow this Question
Related Questions
How should I decide if I should use C#, JavaScript (UnityScript) or Boo for my project? 14 Answers
Are there Indexed Properties in Unity Javascript? 1 Answer
Can I use lambda expressions or anonymous methods in JS? 1 Answer
What are the Syntax Differences in C# and Javascript? 7 Answers
Is there a performance difference between Unity's Javascript and C#? 6 Answers