用getter和setter封装在JavaScript中 [英] Encapsulation in JavaScript with getter and setter

查看:75
本文介绍了用getter和setter封装在JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到这个问题已经被提出,但是已经研究并失败了-抱歉!

I realise that this has been asked but have researched and failed - sorry!

我想尽可能简单地在JS中实现封装。我意识到班上的所有 var都是私人的。

I want to implement encapsulation in JS as simply as possible. I realise that any 'var' in the class will be private.

我只是不确定如何获取和设置任何私有变量的值。在下面的示例中,获取和设置颜色的界面方法不起作用,因为这些功能无法访问对象的私有颜色属性。我找不到一个清晰的示例向我展示如何实现此方法。

I am simply unsure how to GET and SET values of any private var. In the example below the interface methods for GETTING and SETTING 'colour' do not work because those functions cannot access the private 'colour' property of the object. I cannot find a clear example showing me how to implement this.

我什至不确定使用'.prototype'是将这些方法添加到类中的最佳方法。

I am not even sure that using '.prototype' is the best way to add those methods to the class.

谢谢!

<button onclick="testOOP()">Click me</button>

<script>
//<!-- 
function testOOP(){
var v1 = new vehicle(4, "red"); //setting new values during instantiation
var v2 = new vehicle(2, "blue");
showVehDetails(v1);
showVehDetails(v2);
v2.wheels=1;            //demonstrating no encapsulation
showVehDetails(v2);
v2.setcolour("orange");     //using an interface - fails
showVehDetails(v2);
}

    function showVehDetails(v){
        document.write("This vehicle is " + v.getcolour() + " and has " + v.getwheels() + " wheels.<br/>");
    }

    //*************'vehicle' - Class definition**************
    function vehicle(thewheels, thecolour){
        this.wheels = thewheels;            //public property
        var colour = thecolour;             //private property
    }   
    vehicle.prototype = {
        constructor: vehicle,
        getcolour: function(){
            return this.colour;         //but how to create a GETTER for colour?
        },
        getwheels: function(){
            return this.wheels;
        },
        setwheels: function(newwheels){
            this.wheels = newwheels;
        },
        setcolour: function(newcolour){   //and how to create a SETTER for colour?
            this.colour = newcolour;
        }
    }
    //************End class definition************************
   //-->
 </script>


推荐答案

任何 var s不在该构造函数之外。您需要将东西附加到 this 上,以便原型方法可以看到它。 JavaScript没有私有成员的概念。

Any vars declared in a constructor will not exist outside of that constructor. You need to attach things to this in order for prototype methods to see it. JavaScript doesn't have a concept of private members.

function Vehicle(thewheels, thecolour){
  this.wheels = thewheels;
  this.colour = thecolour;
}

Vehicle.prototype = {
  getColour: function() {
    return this.colour;
  }
  // etc
};

...但是您必须问问自己,将吸气剂/定型剂摆在周围会得到什么好处这些成员?在JavaScript中很少使用getter / setter模式。通常,您只是创建公共成员。为成员使用类似 _ 前缀的方式是发出信号的典型方式,即我知道这是可以访问的,但您不应直接对其进行修改。

...but you have to ask yourself, what benefits do you gain around putting getters/setters around these members? It is pretty rare to use the getter/setter pattern in JavaScript. Usually you just create public members. Using things like an _ prefix for members is the typical way to signal "I know this is accessible, but you're not supposed to modify this directly."

如果您确实想使事情真正私有,则需要使用一些关闭技巧:

If you do want to make things truly "private," you'll need to do some tricks with closures:

function Vehicle(theWheels, theColor) {
  return {
    getColour: function() { return theColor; },
    setColour: function(value) { theColor = value; }
  };
}

...但是这种方法的缺点是每个 Vehicle 对象具有这些功能的副本;您将无法获得原型的内存优势。

...but the downside to this approach is every Vehicle object has its own copy of these functions; you don't gain the memory benefits of a prototype.

更新

还应注意:如果您确实想通过包装方法来触发更改成员的逻辑,那么在现代JS中有更好的方法来创建getter和setter:

Also of note: if you do want to trigger logic on changing members by wrapping in methods, there are nicer ways to create getters and setters in modern JS:

function Vehicle(theWheels, theColor) {
  this._wheels = theWheels;
  this._color = theColor;
}

Vehicle.prototype = {
  get color() { return this._color; },
  set color(value) { this._color = value; console.log('Changed color'); },

  get wheels() { return this._wheels; },
  set wheels(value) { this._wheels = value; }
}

呼叫者仅访问 .wheels .color 像普通属性一样,它将调用您的方法。

The caller just accesses .wheels and .color like normal properties, and it will invoke your methods.

这篇关于用getter和setter封装在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆