javascript练习-私有状态

mac2022-06-30  93

在经典的面向对象编程中,经常需要将对象的某个状态封装或隐藏在对象内,只有通过对象的方法才能访问这些状态,对外只暴露一些重要的状态可以直接编写。这是就需要私有状态。

function Range(from, to){ this.from = function(){return from;} this.to = function(){return to;}}Range.prototype = { constructor: Range, includes:function(x){return this.from() <= x && x <= this.to();}, foreach:function(f){ for(var x = Math.ceil(this.from()),max = this.to();x < max;x++)f(x); }, toString:function(){ return "(" + this.from() + "..." + this.to() + ")"; }}

 

转载于:https://www.cnblogs.com/zjtTT/p/5061335.html

最新回复(0)