为什么在JS类`undefined`中声明变量 [英] Why is the variable declared inside the JS class `undefined`

查看:98
本文介绍了为什么在JS类`undefined`中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在JS中使用以下代码中的属性weight创建一个类:

Trying to create a class in JS with the attribute weight in the following code:

function Foo() {
    var weight = 10;
    console.log(weight);
}

当我用实例化它时,var bar = new Foo (); 10 记录到控制台。

When I instantiate it with var bar = new Foo();, 10 is logged to the console.

以后我打电话时 console.log(bar.weight); undefined 被记录到控制台。这是为什么?我的印象是,默认情况下,在JS类中声明的属性是公共的?

When I later call console.log(bar.weight);, undefined is logged to the console. Why is that? I was under the impression that the attributes declared within a JS class were public by default?

推荐答案

这是因为您实际上并没有将 weight 设置为 bar 的属性;它只是在构造函数调用时创建的局部变量(与某些其他语言(例如Java)不同)。要将其创建为属性,您需要使用关键字 this

That's because you haven't actually set weight as a property of bar; it's merely a local variable created upon the constructor call (this differs from some other languages, like Java, for example). To create it as a property, you need to use the keyword this:

function Foo() {
    this.weight = 10;
}

可以设置权重成为 Foo 对象的属性,包括 bar ,因此您应该能够使用 console.log(bar.weight)没问题。

That sets weight to be a property of Foo objects, including bar, so you should be able to use console.log(bar.weight) without issue.

function Foo() {
  this.weight = 10;
}

var bar = new Foo();

document.body.innerHTML = "<code>bar</code>'s weight property is equal to " + bar.weight + ".";

这篇关于为什么在JS类`undefined`中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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