简体   繁体   English

从分配给变量的函数获取要打印的数据

[英]Getting data to print from a function assigned to a variable

// make object properties private

var Bike = function() {
    var speed = 100;                  // private variable

    function addUnit(value) {         // private function
        return value + "KM/H";
    }

    this.getSpeed = function () {     // public function
        return addUnit(speed);
    };
};

var myBike = new Bike();
console.log(myBike);

I'm doing the 'Free Code Camp" thing and this is one of the exercises. Other than the console.log(myBike); this is the solution to their exercise. However, printing out the data isn't part of the exercise and I like to print out the data. So I'm running this code in node.js and I can't get the data to print. When I run my file I get { getSpeed: [Function] } . What I think it should be is 100 KM/H . Could someone show me how to print out the data? 我正在做“免费代码训练”,这是练习之一,除了console.log(myBike);这是他们练习的解决方案,但是,打印数据不是练习的一部分我喜欢打印数据,所以我在node.js中运行此代码,但我无法获取要打印的数据。运行文件时,我得到{ getSpeed: [Function] } 。应该是100 KM/H有人可以告诉我如何打印数据吗?

myBike is an object of type Bike , so what you're printing is actually the instance of your "class" called Bike, you need to do myBikeBike类型的对象,因此您要打印的实际上是名为“ Bike”的“类”的实例,您需要

console.log(myBike.getSpeed())

which is to say "invoke the getSpeed method which exists on my Bike object" 也就是说“调用存在于我的Bike对象上的getSpeed方法”

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

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