• JavaScript中的Get和Set访问器


    今天要和大家分享的是JavaScript中的Get和Set访问器,和C#中的访问器非常相似。

    标准的Get和Set访问器的实现

     
    function Field(val){  
        this.value = val;  

    Field.prototype = {  
        get value(){  
            return this._value;  
        },  
        set value(val){  
            this._value = val;  
        }
    };
    var field = new Field("test");
    field.value="test2";
    //field.value will now return "test2"

    在如下浏览器能正常工作:

    我们常用的实现方法可能是这样的:

    function Field(val){
        var value = val;
        
        this.getValue = function(){
            return value;
        };
        
        this.setValue = function(val){
            value = val;
        };
    }
    var field = new Field("test");
    field.setValue("test2")
    field.getValue() // return "test2" 

    在DOM元素上Get和Set访问器的实现

    HTMLElement.prototype.__defineGetter__("description", function () { 
              return this.desc; 
    }); 
    HTMLElement.prototype.__defineSetter__("description", function (val) { 
              this.desc = val; 
    }); 
    document.body.description = "Beautiful body"; 
    // document.body.description will now return "Beautiful body";

    在如下浏览器能正常工作:

    通过Object.defineProperty实现访问器
         将来ECMAScript 标准的扩展对象的方法会通过Object.defineProperty来实现,这也是为什么IE8就是通过 这种方法来实现get和set访问器,看来微软还是很有远见的,遗憾的是目前只有IE8+和Chrome 5.0+支持,其它的浏览器都不支持,而且IE8+也只支持DOM元素,不过将来的版本将和Chrome一样支持普通的Javascript对象。


    DOM元素上的Get和Set访问器的实现

    Object.defineProperty(document.body, "description", {   
        get : function () {       
            return this.desc;  
        },    
        set : function (val) { 
            this.desc = val;    
        } 
    }); 
    document.body.description = "Content container"; 
    // document.body.description will now return "Content container"

    在如下浏览器能正常工作:

    普通对象的Get和Set访问器的实现

    var lost = {
        loc : "Island"
    };    
    Object.defineProperty(lost, "location", {
        get : function () {
            return this.loc;
        },
        set : function (val) {
            this.loc = val;
        }
    });
    lost.location = "Another island";
    // lost.location will now return "Another island"

    在如下浏览器能正常工作:

     

    本文总结

      尽管微软的IE只是支持了Object.defineProperty,没有完美的实现Get和Set访问器,但是我们已经看到了IE有了很大 的进步,特别是刚发布的IE9使用的新的javascript引擎,支持HTML5和CSS3,支持硬件加速等等,相信有一天各个浏览器都能完全拥抱标 准,带来一个完美的WEB世界。

    参考文献:

    1. Getters and setters with JavaScript

    2. JavaScript Getters and Setters

    来源:http://www.cnblogs.com/lhb25/archive/2010/09/19/1830724.html

  • 相关阅读:
    Python基础04_str_方法
    Python基础03_pycharm
    Python基础02_基本数据类型_以及while
    Python基础01_介绍_HelloWorld
    Linux基础知识_Shell编程笔记
    python基础之centos6.5 升级 python2.7, 安装pip, MySQLdb
    不得不补:PHP的JSON, SQL
    JS类小功能
    1083.是否存在相等的差(20)
    c++ 的vector sort遇到栈错误
  • 原文地址:https://www.cnblogs.com/zhuyang/p/4366289.html
Copyright © 2020-2023  润新知