JavaScript 中的封装

发布于 2024-09-27 17:34:48 字数 870 浏览 2 评论 0原文

我对 Javascript 还很陌生,我的 SO 个人资料将证明这一点。

我刚刚阅读了一些教程,发现了一些我在 Javascript 中应用的面向对象和封装方面并不完全理解的内容。

该教程指出 Javascript 对象可以这样声明:

var myCustomObject = new Object();

并且您可以给它这样的实例变量:

myCustomObject.myVariable = "some value";
myCustomObject.myOtherVariable = "deadbeef";

最后,它指出您可以创建一个模板函数来创建新对象,如下所示:

function CustomObject(myVariable, myOtherVariable)
{
    this.myVariable = myVariable;
    this.myOtherVariable = myOtherVariable;
}

我也知道您可以创建和分配尚不存在的变量的值,因此被隐式声明,如示例所示,其中 myCustomObject 没有 myVariable,但现在有了。

所以,我的问题是:有什么办法可以防止在代码中的其他位置添加新变量。如果我试图了解一个对象如何工作以及我可以/应该用它做什么,我可能永远不会看到其他 .js 文件中很可能存在的变量添加,因此无法完全理解该对象。 ..

另外,我怎么知道刚刚创建的某个对象不会突然在代码中添加了 60 个变量,而这些变量在创建时根本没有提到?

如果可以“随意”添加更多内容,那么您如何能够一眼就理解一个对象可以包含什么内容?

I'm pretty new to Javascript, as my SO profile will attest.

I've just been reading up on a few tutorials and come across something I don't totally understand in regards to Object Orientation and Encapsulation when applied with Javascript.

The tutorial stated that Javascript objects can be declared like this:

var myCustomObject = new Object();

And that you can give it instance variables like this:

myCustomObject.myVariable = "some value";
myCustomObject.myOtherVariable = "deadbeef";

Finally, it states that you can create a template function to create new objects like this:

function CustomObject(myVariable, myOtherVariable)
{
    this.myVariable = myVariable;
    this.myOtherVariable = myOtherVariable;
}

I also know that you can create and assign values to variables that do not yet exist and as a result are declared implicitly, as is seen in the example, where myCustomObject didn't have a myVariable, but now it does.

So, my question is: What is there to prevent new variables from being added at some other point in the code. If I'm trying to learn how an object works and what I can/should do with it, I may never see the variable additions that could well be in some other .js file, and thus not have a full understanding of the object...

Also, how do I know that some object that has just been created won't suddently turn out to have 60 more variables added later on in code that weren't mentioned at all at creation time?

How are you meant to be able to understand what an object can contain at a glance if more can just be added to it "willy nilly"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

那小子欠揍 2024-10-04 17:34:48

我不太相信我要引用《蜘蛛侠》的话,但是……

能力越大,责任越大

JavaScript 强大而灵活,给程序员很大的自由。它不具备旨在阻止程序员编写糟糕代码的功能。当你编写 JavaScript 时,你有责任确保代码是好的,而不是语言。

I can't quite believe that I'm about to quote Spiderman but …

With great power comes great responsibility

JavaScript is powerful and flexible and gives programmers lots of freedom. It doesn't come with features designed to stop programmers writing bad code. When you write JavaScript, you are responsible for making sure the code is good, not the language.

别在捏我脸啦 2024-10-04 17:34:48

你不能,没有什么可以阻止我对你的对象做任何我想做的事;)但是,你不必使用这些变量..

你可以做的一件事就是使用范围,例如:

function myConstructor()
{
  var myState = {}; //Create new, empty object
  myState.text = "Hello World!";
  this.say = function() {
    alert(myState.text);
  };
}

在这个简单的例子中您可以将内部变量存储在 myState 中(或“var text = '';”等),并且它们无法从外部访问,因为它们不是对象的成员,它们只是函数中的私有变量。而且,正如您所看到的,函数 say 仍然可以访问它。

You can't, there's nothing that stops me from doing whatever I want with your objects ;) However, you don't have to use those variables..

One thing you can do is to play with scopes, example:

function myConstructor()
{
  var myState = {}; //Create new, empty object
  myState.text = "Hello World!";
  this.say = function() {
    alert(myState.text);
  };
}

In this simple example you can store you internal variables in myState (or "var text = '';" etc) and they aren't accessible from outside since they are not members of an object, they are just private variables in your function. And, as you can see, the function say still has access to it.

一抹淡然 2024-10-04 17:34:48

简短的回答:绝对没有。

长答案:

Javascript 在很多方面都是一种动态语言,而不仅仅是类型系统。该语言中的每个类似对象的东西基本上都是一个关联数组,可以根据需要添加到其中。变量(显然可以包含这些对象之类的东西)仅存在于其函数范围内。

您可以使用这一点来模拟私有成员,这可以在一定程度上缓解这种情况。我之前已经多次发布过这样的示例,因此我将向您推荐有关该主题的权威指南: http://javascript.crockford.com/private.html

至于以您不希望的方式向对象添加新成员,实际上没有什么可做的,这就是语言的方式。

事后思考:

当接触 javascript 时,请记住它实际上不是一种 OOP 语言,它是函数/原型与一些 OOP 思想的奇怪而美妙的组合。不要被类似 java 的语法所愚弄,如果你发挥这些语言的优势而不是 ape java,你会过得更好。

Short answer: Absolutely nothing.

Long answer:

Javascript is a dynamic language in more ways than just the type system. Every object like thing in the language is basically an associative array which can be added to as you please. Variables (which can obviously contain these object like things) exist only within their function scope.

You can use this point to simulate private members which can tame the situation somewhat. I've posted examples of this several times before so I'll just refer you to the definitive guide on the subject: http://javascript.crockford.com/private.html.

As far as adding new members to objects in a way you did not intend goes, there's really nothing to be done that's just the way the language is.

Afterthought:

When approaching javascript try to remember it's really not an OOP language it's a weird and wonderful mix of functional / prototypical with a few OOP ideas. Don't be fooled by the java like syntax, you'll have a much better time if you play to the languages strengths rather than ape java.

゛清羽墨安 2024-10-04 17:34:48

Javascript 对象是转换器(TM),它们可以从一种形式转变为另一种形式。

实际上,这只会丰富对象,而不会造成伤害。例如,它允许人们升级现有的“类”,而不是子类化或再次装饰实例,从而无需创建更多“类”。举个例子:

var Vehicle = function(){}

var factory = {
    create: function(name, props){
        var v = new Vehicle();
        v.type = name;
        for(var prop in props) {
            v[prop] = props[prop];
        }
    }
}

var bike = factory.create('Bike', {
    wheels: 2
});

var car = factory.create('Car', {
    wheels: 4,
    doors: 5,
    gear: 'automatic'
});

var plane = factory.create('Airplane', {
    wings: 2,
    engines: 4
});

想象一下如果没有动态对象,上面的代码会怎样,而你却无法做到这一点:

// lets paint our car
car.color = 'candy red';
// bling!
car.racingStripes = true;
car.mirrorDice = true;
car.furryChairs = true;

你可以以更简单的方式丰富/个性化对象。

Javascript objects are transformers (TM), they can turn from one form to another.

In practise this only happens to enrich objects, never to cause harm. It allows one to for example upgrade an existing 'class' rather then subclassing or to decorate instances again removing the need to create even more 'classes'. Take the following example:

var Vehicle = function(){}

var factory = {
    create: function(name, props){
        var v = new Vehicle();
        v.type = name;
        for(var prop in props) {
            v[prop] = props[prop];
        }
    }
}

var bike = factory.create('Bike', {
    wheels: 2
});

var car = factory.create('Car', {
    wheels: 4,
    doors: 5,
    gear: 'automatic'
});

var plane = factory.create('Airplane', {
    wings: 2,
    engines: 4
});

Imagine what the code above would take without dynamic objects and you couldn't do this:

// lets paint our car
car.color = 'candy red';
// bling!
car.racingStripes = true;
car.mirrorDice = true;
car.furryChairs = true;

You get to enrich/personalize objects in a much easier way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文