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 序号的值不能比当前小
  • 相关阅读:
    6.1成果(冲刺2.10)
    5.31成果(冲刺2.9)
    5.30成果(冲刺2.8)
    5.29成果(冲刺2.7)
    5.28成果(冲刺2.6)
    5.27成果(冲刺2.5)
    5.26成果(冲刺2.4)
    5.25成果(冲刺2.3)
    Nginx location匹配后 跳转问题
    记一次centos上发布core,访问502的bug
  • 原文地址:https://www.cnblogs.com/rellame/p/5007307.html
Copyright © 2011-2022 走看看