zoukankan      html  css  js  c++  java
  • javascript权威指南笔记--javascript语言核心(五)--getter和setter属性

    getter和setter属性:

    var p = {
        x:1.0,
        y:1.0,
        get r(){
            return Math.sqrt(this.x*this.x + this.y * this.y);
        },
        set r(newValue){
            var oldValue = Math.sqrt(this.x*this.x + this.y * this.y);
            var ratio = newValue / oldValue;
            this.x *= ratio;
            this.y *= ratio;
        },
        get theta(){
            return Math.atan2(this.y,this.x);
        }
    };
    console.log(p.r);//1.4142135623730951
    console.log(p.x);//1
    console.log(p.y);//1
    console.log(p.theta);//0.7853981633974483
    p.r = 10;
    console.log(p.r);//10
    console.log(p.x);//7.071067811865475
    console.log(p.y);//7.071067811865475
    console.log(p.theta);//0.7853981633974483

    r是可读写的存取属性,而theta是只读属性,它只有getter方法。和数据属性一样,存取属性是可以继承的。

    存取器属性用于智能检测属性:

    var serialnum = {
            $n : 0,
            get next(){return this.$n++},
            set next(n){
                if(n > this.$n) this.$n = n;
                else throw "序号的值不能比当前小";
            }
        }
    console.log(serialnum.$n);//0
    console.log(serialnum.next);//0
    serialnum.next = 4;
    console.log(serialnum.$n);//0
    console.log(serialnum.next);//4
    serialnum.next = 3;
    console.log(serialnum.$n);
    console.log(serialnum.next);//Uncaught 序号的值不能比当前小
  • 相关阅读:
    TSYS2.0 碎片工作原理
    回旋。悲哉、哀哉
    Sql高级操作
    你是我最愛的人
    TSYS2.0标签说明
    TSYS:Tkl_TemplateClass 类调用详解
    CMS设计和CMS选型(内容管理系统)
    TSYS2.0 Beta与Tsys 1.1等众多版本下载
    TsysV1.1 系统文件清单介绍
    伪装成Google Bot突破收费页面
  • 原文地址:https://www.cnblogs.com/rellame/p/5007307.html
Copyright © 2011-2022 走看看