问题
This is how i am defining a simple class with instance variables and instance methods.
ExampleClass = SC.Object.extend({
foo:undefined,
bar: function() {
this.foo = "Hello world";
console.log( this.foo );
}
}
// test
var testInstance = ExampleClass.create();
testInstance.bar(); // outputs 'Hello world'
Could anyone help me out with a similar example of class variable (or similar behavoir), and class method?
Thanks
回答1:
A class Method/Property would be done like:
ExampleClass = SC.Object.extend({
foo:undefined,
bar: function() {
this.foo = "Hello world";
console.log( this.foo );
}
}
ExampleClass.mixin({
classFoo: "foo",
classBar: function() {
return "Bar";
}
})
Then you can access it like:
ExampleClass.classFoo
But don't forget that when accessing a property (or computed property) on an instance, that you need to use .get()
like:
var example = ExampleClass.create();
// Good
example.get('foo');
example.set('foo', 'baz');
// BAD!! Don't do this, or Bindings/ Observes won't work.
example.foo;
example.foo = 'baz';
来源:https://stackoverflow.com/questions/5103577/basic-sproutcore-class-method-class-variables-help