简体   繁体   English

使用闭包创建私有属性 javascript

[英]using closure to make private properties javascript

I have this prompt on code wars我有关于代码战争的提示

"There's no such thing as private properties on a javascript object! But, maybe there are? “javascript对象上没有私有属性这样的东西!但是,也许有?

Implement a function createSecretHolder(secret) which accepts any value as secret and returns an object with ONLY two methods"实现一个函数 createSecretHolder(secret),它接受任何值作为秘密并返回一个只有两种方法的对象”

I'm pretty sure it wants me to use closures to achieve this and I have read about how to do this here:我很确定它希望我使用闭包来实现这一点,我已经在此处阅读了有关如何执行此操作的信息:

Private variables and closures 私有变量和闭包

https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Contributor_s_Guide/Private_Properties https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Contributor_s_Guide/Private_Properties

This is my code:这是我的代码:

function createSecretHolder(secret) {
  return {
    var _secret = secret;
    this.getSecret = function(){
      return _secret;
    }

    this.setSecret = function(secret){
      _secret = secret;
    }
  }
}

However, I get this error:但是,我收到此错误:

[eval]:6
 var _secret = secret;
              ^
SyntaxError: Unexpected token =
    at Object. ([eval]-wrapper:6:22)
    at 
    at evalScript (node.js:536:25)
    at startup (node.js:80:7)
    at node.js:906:3

I tried to make an object literal with a private value to hold the value of secret and mostly followed the examples from the sources I listed above.我尝试创建一个带有私有值的对象文字来保存 secret 的值,并且主要遵循我上面列出的来源中的示例。 How do I create a closure with ONLY two methods to get and set data and where do I store the value of secret without adding another property?如何仅使用两种方法创建闭包来获取和设置数据,以及在不添加其他属性的情况下存储秘密值的位置?

You are trying to return an object literal, in which you cannot have an assignment statement. 您正在尝试返回对象文字,在该文字中不能有赋值语句。 To have the closure property, you need to store the variable in the function scope, like this 要具有闭包属性,您需要将变量存储在函数范围内,如下所示

function createSecretHolder(secret) {
    var _secret = secret;

    return {
        getSecret: function() {
            return _secret;
        },

        setSecret: function(secret) {
            _secret = secret;
        }
    }
}

Now, _secret is in the scope of the getSecret and setSecret functions, because of the closure property. 现在,由于闭包属性, _secretgetSecretsetSecret函数的范围内。 So they can access it. 这样他们就可以访问它。

The problem is return keyword actually returns object with a structure which you didn't follow. 问题是return关键字实际上返回具有您未遵循的结构的对象。 try this: 尝试这个:

function createSecretHolder() {
  var _secret = secret;
return {

    getSecret : function(){
      return _secret;
    }
,
    setSecret : function(secret){
      _secret = secret;
    }
  }
}

Using _ to prepend a property is a common naming convention JavaScript developers follow to show the intention that the property should not be altered, and it is definitely related to this prompt, but it seems like it is not hinting that it's needed and it may not be required for this challenge specifically.使用 _ 来添加属性是 JavaScript 开发人员遵循的常见命名约定,以表明不应更改该属性的意图,这肯定与此提示有关,但似乎并未暗示需要它,也可能不需要需要专门针对这一挑战。

The SyntaxError you're seeing is related to the _secret initialization being within the object literals rather than outside.您看到的 SyntaxError 与 _secret 初始化在对象文字内而不是在外部有关。 Object literal syntax is different from variable declaration & assignment and should be mixed.对象字面量语法与变量声明和赋值不同,应该混合使用。 You can move the var _secret = secret;你可以移动var _secret = secret; to outside of and before the return statement (but still inside of the function createSecretHolder).在 return 语句的外部和之前(但仍在函数 createSecretHolder 内部)。 (Super Hornet is right, but his code is missing the secret parameter, so his code would get a Reference error saying that secret is not defined.) While your attempt is slightly more declarative, you can actually do without the const _secret = secret . (Super Hornet 是对的,但他的代码缺少secret参数,所以他的代码会得到一个 Reference 错误,说 secret 未定义。)虽然您的尝试更具声明性,但实际上您可以不用const _secret = secret The first thing that the function does is to pair its argument with its parameter, in this case, declaring secret and assigning the input to it.该函数所做的第一件事是将其参数与其参数配对,在这种情况下,声明秘密并将输入分配给它。 So it is already "in closures".所以它已经“关闭”了。

Here's my take and it works almost the same, except I like to include the console.log() into my functions that I'm expecting to see a result.这是我的看法,它的工作原理几乎相同,只是我喜欢将 console.log() 包含到我希望看到结果的函数中。

function createSecretHolder(secret) {
  // input: secret 
  // output: object (with only 2 methods) 
  
  return {
    getSecret() { console.log(secret) },
    setSecret(input) { secret = input }
  }
}

const obj1 = createSecretHolder(5);
obj1.getSecret() // => 5
obj1.setSecret(2)
obj1.getSecret() // => 2

Same as:与...一样:

function createSecretHolder2(secret) {
  return {
    getSecret() { return secret },
    setSecret(input) { secret = input }
  }
}

const obj2 = createSecretHolder2(91);
console.log(obj2.getSecret()) // => 91
console.log(obj2.setSecret(82)) // => undefined
obj2.setSecret('new Secret') // logs nothing, returns undefined
obj2.getSecret() // logs nothing, returns 'new Secret'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM