在 JS 类内部和外部打印值

问题描述 投票:0回答:3

我写了一个练习类,谁能告诉我为什么

console.log()
打印2而不是1?

function hnclass(){
    var h=1;
    function print(){
        console.info(h); //here it print 1
    }
    return {
        item:h,
        printout:print
    }
}

hc=new hnclass();
hc.item=2;
hc.printout();
console.log(hc.item); //here it print 2 

使用

hc.item=2;
我更改了
item
的值,所以当我调用打印函数时,它应该打印出
2
。在这种类中,是否可以在没有 setter 函数的情况下设置值?

javascript class
3个回答
2
投票

谁能告诉我为什么它打印 2 而不是 1

因为设置变量或属性的值永远不会更改另一个变量或属性的值。这是一个简化的示例:

var a = 1;
var b = a;
a = 42;

a
分配新值不会更改
b
的值,即使
b
a
最初的值相同。
在您的情况下,为
hc.item
赋值并不会改变
h
的值。

我在想在这种类中没有setter函数设置值是否可能?

是的,如果您还访问

x.item
内的
print

function hnclass(){
    var h=1;
    function print(){
        console.info(obj.item);
    }
    var obj = {
        item:h,
        printout:print
    };
    return obj;
}

但是,整个设置与 OOP 或类没有任何关系。也许面向对象 JavaScript 简介可以帮助您更好地理解问题。


1
投票

你写的不是一个类,而是一个函数。这是你明确的错误。

  1. 您没有使用
    this
    将变量的范围限定在类中,而是私有变量。
  2. 您添加了一个覆盖您的类定义的返回语句。如果你添加

    console.info(hc instanceof hnclass);

您会看到您的变量

hc
不是您的类的实例。

这是更正后的代码。

function hnclass () {
    var self = this;
    this.item = 1; 
    this.printout = function print () {
        console.info(this.item); 
    }
}
var hc = new hnclass();
hc.printout(); // will display 1
hc.item = 4;

console.info(hc  instanceof hnclass); // will display true
hc.printout(); // will display 4
console.log(hc.item); // will display 4

我建议你更多地学习闭包、作用域、函数与类的区别,以及如何测试变量是否属于带有instanceof的类。


0
投票

在“类”声明中,

h
是一个局部变量。如果你想创建一个属性,你必须做类似的事情:

function hnclass () {
    this.item = 1; // Here item is a attribute of your class
    this.printout = function print () {
        console.info(this.item); // Use this.item instead of h
    }
}
hn = new hnclass () ;
hn.printout() ;
hn.item = 4 ;
hn.printout() ;

这是一个非常简单的示例,您可以使用

prototype
获得更有条理的代码。

© www.soinside.com 2019 - 2024. All rights reserved.