【问题标题】:Basic Sproutcore: class method, class variables helpBasic Sproutcore:类方法、类变量帮助
【发布时间】:2011-02-25 22:15:22
【问题描述】:

这就是我用实例变量和实例方法定义一个简单类的方式。

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'

谁能帮助我提供类变量(或类似行为)和类方法的类似示例?

谢谢

【问题讨论】:

    标签: sproutcore


    【解决方案1】:

    一个类方法/属性可以这样完成:

    ExampleClass = SC.Object.extend({
      foo:undefined,
      bar: function() {
        this.foo = "Hello world";
        console.log( this.foo );
      }
    }
    
    ExampleClass.mixin({
      classFoo: "foo",
      classBar: function() {
        return "Bar";
      }
    })
    

    然后你可以像这样访问它:

    ExampleClass.classFoo
    

    但不要忘记,在访问实例上的属性(或计算属性)时,您需要使用.get(),例如:

    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';
    

    【讨论】:

    • 谢谢,正是我想要的。厚颜无耻的问题:- 如果一个访问器(get() 或 set())用于所有属性,您是否知道是否可以使用自定义 getter 或 setter?
    • 是的,这是我们获得/设置的另一个主要原因。看看这里:guides.sproutcore.com/core_concepts.html#computed-properties
    • 我不清楚这是否可行——我认为有一个访问器函数可以根据调用上下文同时充当 getter 和 setter,但它确实很好用。感谢您的帮助。
    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多