gpt4 book ai didi

Javascript:通过返回匿名对象实现私有(private)变量

转载 作者:行者123 更新时间:2023-12-02 17:17:06 25 4
gpt4 key购买 nike

该示例实现了矩形的私有(private)变量。变量 myLength 和 myWidth 对于不同的实例是不同的。那么为什么不推荐这种方法呢?

var rectangle = function() {
var myLength = 8;
var myWidth = 6;

var getMyLength = function () {
return myLength;
};

var setMyLength = function (value) {
myLength = value;
};

var getMyWidth = function () {
return myWidth;
};

var setMyWidth = function (value) {
myWidth = value;
};

var drawFigure = function() {
console.log("Draw invoked for figure: " +
getMyLength() + " * " + getMyWidth());
};

return {
getMyLength: getMyLength,
setMyLength: setMyLength,
getMyWidth: getMyWidth,
setMyWidth: setMyWidth,
drawFigure: drawFigure
}
};

然后我们按如下方式使用它:

var myRectangle = new rectangle();

myRectangle.drawFigure(); // Draw invoked for figure: 8 * 6

myRectangle.setMyLength(3);

myRectangle.setMyWidth(5);

myRectangle.drawFigure(); // Draw invoked for figure: 3 * 5

var myRectangle1 = new rectangle();

myRectangle1.drawFigure(); // Draw invoked for figure: 8 * 6

最佳答案

在我看来,私有(private)变量被高估了。你真的需要向程序员隐藏一些事情吗?不。即使您将所有私有(private)变量公开,会有什么不同呢?事实上,我主张将一切公开,因为:

  1. 这将使调试更容易。如果您 console.log 一个对象,那么您可以检查其公共(public)属性,这使得调试更容易,因为您可以看到对象的状态.
  2. 您不需要创建不必要的闭包。如果您想要一个私有(private)变量并且还希望它可以通过公共(public)方法访问,那么您必须创建一个闭包(每个实例一个) 。如果您将您的属性(property)公开,那么您就不需要关闭。您可以将方法放在原型(prototype)上。因此,每个类只有一个方法,由所有实例共享。
  3. 您不需要创建不必要的 getter 和 setter。将变量设为私有(private)并允许任何人使用 getter 和 setter 函数修改它有什么意义?您不妨将变量公开。

    以我的拙见, getter 和 setter 仅对幻像属性有用:

    var Person = defclass({
    constructor: function (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    },
    getFullName: function () {
    return this.firstName + " " + this.lastName;
    },
    setFullName: function (fullName) {
    var name = fullName.split(" ");
    this.firstName = name[0];
    this.lastName = name[1];
    }
    });

因此,在我看来,您应该按如下方式编写 Rectangle 类:

var Rectangle = defclass({
constructor: function (width, height) {
this.width = width;
this.height = height;
}
});

然后我们按如下方式使用它:

var rectA = new Rectangle(8, 6);

console.log(rectA); // { width: 8, height: 6 }

rectA.width = 3;
rectA.height = 5;

console.log(rectA); // { width: 3, height: 5 }

var rectB = new Rectangle(8, 6);

console.log(rectB); // { width: 8, height: 6 }

最后是defclass的定义:

function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

这就是我对如何在 JavaScript 中创建对象的两点看法。

关于Javascript:通过返回匿名对象实现私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24338135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com