简体   繁体   English

什么是我的代码错误 - 面向对象的JavaScript

[英]whats wrong with my code - object oriented javascript

I am new to object oriented programming in JavaScript. 我是JavaScript中面向对象编程的新手。 I'm not sure what's wrong with following program: 我不确定以下程序有什么问题:

function Sample() {
    var data = "one";

    var getData = function () {
        return data;
    };

    this.getter = function () {
        getData();
    };
}

var s = new Sample;

alert(s.getter()); // alerts undefined

The above program doesn't work as I expected it to, but the following program does: 上述程序不能像我预期的那样工作,但是以下程序可以:

function sample() {
    var data = "one";

    var getData = function () {
        return data;
    };

    this.getter = function () {
        return getData();
    };
}

var s = new Sample;

alert(s.getter()); // alerts "one"

Why is it so? 为什么会这样?

You need to use, because your getter method is nor returning any value to the caller. 您需要使用,因为您的getter方法也没有向调用者返回任何值。

In your getter , you are calling getData method which return the value of data but that value is not sent back the the caller of getter 在你的getter ,你正在调用getData方法,该方法返回data的值,但该值不会被发送回getter的调用者

this.getter = getData

or 要么

this.getter = function () {return getData();}

In the first sample of code you are not returning any value - just calling the function getData . 在第一个代码示例中,您没有返回任何值 - 只需调用函数getData The return value does not 'propagate' further (is not being passed further as return value for getter function. 返回值不会'进一步'传播(不会作为getter函数的返回值进一步传递)。

// Here you are just calling getData
this.getter = function () {getData();} 

// Here you are returning the value returned by getData function
this.getter = function () {return getData();} 

The answer is there in your code only. 答案仅在您的代码中。 You are not returning in the first case. 你没有在第一种情况下回来。 How will you get it in alert if you don't return. 如果你不回来,你将如何保持警惕。 Your second snippet fixes that. 你的第二个片段修复了这个问题。

You are not returning anything from first getter of sample . 不必返回从第一什么gettersample That's why you are getting undefined 这就是你undefined的原因

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

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