Javascript函数defineProperty, etc.

在C#中,我们定义Class的时候,往往涉及到class的property,如:

  class A{

    public string SampleProperty{

      get;

      set;

    }

  }

那么,我们在Javascript函数体里面,是否也能如此类似去定义呢?答案是肯定的。

借助Javascript的Object.defineProperty,我们可以像这么做:

  

  function DemoFunction(){
       this.sampleProperty="defaultValue";
       Object.defineProperty(this,"SampleProperty",{

      get:function(){

        return this.sampleProperty;

      },

      set:function(value){

        var oldvalue=this.sampleProperty;

        this.sampleProperty=value;

        this.SamplePropertyValueChanged(oldvalue,value);

      }

    })

    this.SamplePropertyValueChanged = function(oldvalue, newvalue) {

      alert("The value of the property \"SampleProperty\" changed! From \"" + oldvalue + "\" to \"" + newvalue + "\"");          

    }
    }

使用时:

  var demoFuncInstance=new DemoFunction();

  alert(demoFuncInstance.SampleProperty);  //defaultValue

  demoFuncInstance.SampleProperty="Hello, world!";

  //The value of the property "SampleProperty" changed! From "defaultValue" to "Hello, world!"

  alert(demoFuncInstance.SampleProperty);  //Hello, world!

posted @ 2015-12-17 16:06  我喂自己袋盐_1989  阅读(285)  评论(0)    收藏  举报