JavaScript-私人成员解释? [英] JavaScript - Private members explanation?

查看:51
本文介绍了JavaScript-私人成员解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Crockford的这篇文章: http://www.crockford.com/javascript/private.html

Im reading this article from Crockford: http://www.crockford.com/javascript/private.html

在他谈论私有的部分中,他说:

And in the section where he talks about Private, he says:

私有成员由构造函数组成.构造函数的普通var和参数成为私有成员.

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.

现在,如果我在脚本中执行此操作:

Now if I do this in my script:

"use strict"
function car(brand) {
    this.brand = brand;
    var year = 2012;
    var color = "Red";
}

var bmw = new car("BMW");
console.log(bmw.brand); // BMW -> VISIBLE ?!?

我可以轻松访问通过构造函数传递的属性!有人可以更好地解释这一点,通过构造函数传递的这些变量不应该是私有的吗?

I can easily access property that was passed through constructor! Can someone explain this better, shouldn't these variables passed through constructor be private?

谢谢!

推荐答案

我认为您误解了这些信息.它没有说私有方法是那些通过"构造函数的方法,而是说那些是由"构造函数制造"的方法.

I think you've mis-interpreted that bit of information. It doesnt say that private methods are those that are "passed through" the constructor, it says its those that are "made by" the constructor.

为清楚起见,请看以下内容:

To be clear, look at this:

function car(brand) {
    var year = 2012;
    var color = "Red";
}

具有 3 个私有变量. brand year color .通过添加此行

That has 3 private variables. brand,year and color. By adding this line

this.brand = brand

您正在创建一个公共属性,并从您的私有变量中为其分配值.如果您更清楚地将公共财产和私有变量命名为

You are creating a public property and assigning it the value from your private variable. That you've named the public property and the private variable the same thing is neither here nor there, if it makes it clearer think of it as

this.publicBrand = brand

这篇关于JavaScript-私人成员解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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