JavaScript - 属性生命周期和构造方法触发

时间:2016-04-29 00:22:54

标签: javascript javascript-objects

我真的希望Date.now()可用作属性,而不是函数调用或方法。换句话说,我希望clock.now.go返回一个unix时间戳。我无法让它发挥作用。返回的时间戳与原始呼叫停滞不前。下面是显示控制台结果的代码。是否可以通过调用属性来触发新的时间戳,或者是函数调用,即'()'需要?

//Revealing Module Pattern (Public & Private) 
var clock = (function() {

    // object to expose as public via return
    var pub = {};

    //constructor function
    function Now() {
        this.getNow = function() {
            return ( Date.now() );
        };
        this.go = this.getNow();
    }

    //private
    var now = new Now();
    //public
    pub.test1 = now;
    pub.test1.go;  //clock.test1.go returns 1461888755076
    pub.test1.getNow();  //clock.test1.getNow() returns 1461888767477 (GOOD)
    pub.test2 = now.getNow();  //clock.test2 returns 1461888755076 (STALE)
    pub.test3 = now.go;  //clock.test3 returns 1461888755076 (STALE)
    //Return just the public parts
    return pub;
}());

2 个答案:

答案 0 :(得分:3)

如果您希望将其显示为属性,但实际上是实时函数调用,则可以使用Javacript getter

w[i]

或者,它可以浓缩为:

//Revealing Module Pattern (Public & Private) 
var clock = (function() {

    // object to expose as public via return
    var pub = {};

    Object.defineProperty(pub, "now", {
        get: function () { 
            return Date.now();
        }
    });
    return pub;
}());

console.log(clock.now);   // returns live time

或者,即使只是这个(没有封闭的模块模式):

//Revealing Module Pattern (Public & Private) 
var clock = (function() {

    // object to expose as public via return
    var pub = { 
        get now() { 
            return Date.now();
        }
     };
     return pub;
}());

console.log(clock.now);   // returns live time

答案 1 :(得分:1)

你可以用这样的吸气剂

来做

  <DataTemplate>
    <ViewCell>
      <ViewCell.View>
        <StackLayout Orientation="Horizontal">
            Label Text="{Binding Note}" />
          </StackLayout>
      </ViewCell.View>
    </ViewCell>
  </DataTemplate>