在javascript对象

时间:2015-05-13 16:07:57

标签: javascript object coffeescript object-literal

我猜这应该很简单,但是我被困住了。如何在另一个原型对象中存储对方法的引用(在本例中为actions)?以下面的方式,我的someFn和anotherFn方法未定义。

class MyClass

  constructor: ->
    console.log @actions # returns
    # returns:
    # Object {someFn: undefined, anotherFn: undefined, someText "I am some text"}

  actions:
     someFn: @someFn
     anotherFn: @anotherFn
     someText: 'I am some text'

  someFn: ->
    console.log 'I am some function'

  anotherFn: ->
    console.log 'I am another function'

我使用的是CoffeeScript,但对于任何普通的JS,我们都在那里 -

  MyClass = function MyClass() {
    console.log(this.actions);
  }

  MyClass.prototype.actions = {
    someFn: MyClass.someFn,
    anotherFn: MyClass.anotherFn,
    someText: 'I am some text'
  };

  MyClass.prototype.someFn = function() {
    return console.log('I am some function');
  };

  MyClass.prototype.anotherFn = function() {
    return console.log('I am another function');
  };

1 个答案:

答案 0 :(得分:3)

你不能在原型上拥有对象。您将要创建一个实例属性:

try{
        CaseEntities caseEntities = new CaseEntities();
        // Get an existing Entity (this line works)
        var entity = caseEntities.RecordsDistributionPreferences.Find("0001");
        // Change a field
        entity.ModifiedBy = "duncan";

        // get row version before save
        byte[] rowVersionBefore = entity.RowVersion;

        // Save Changes (this next line throws null reference exeption)
        caseEntities.SaveChanges();

        // get row version after save
        byte[] rowVersionAfter = entity.RowVersion;

        // Check that row version are different
        Assert.AreNotEqual(BitConverter.ToInt64(rowVersionBefore.Reverse().ToArray(), 0), BitConverter.ToInt64(rowVersionAfter.Reverse().ToArray(), 0));
    }
catch (NullReferenceException ex){

}

如果由于某种原因你确实需要一个带有原型函数的对象,请使用class MyClass constructor: -> @actions = someFn: @someFn anotherFn: @anotherFn someText: 'I am some text' console.log @actions # works as expected someFn: -> console.log 'I am some function' anotherFn: -> console.log 'I am another function' 来访问它们(在创建::对象的静态上下文中):

action