Basic Sproutcore: class method, class variables help

我怕爱的太早我们不能终老 提交于 2019-12-11 17:54:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!