简体   繁体   English

为什么这会返回undefined -javascript

[英]why does this return undefined - javascript

i'm pretty new to js. 我对js很新。 i'm sorry if this sounds dumb. 如果这听起来很蠢,我很抱歉。 but why does the following code return "undefined" 但为什么下面的代码返回“undefined”

function NewPerson(name, age, sex){
    this.name = name;
    this.age = age;
    this.sex = sex;

    this.getName = function(){
        //alert(this.name);
        alert("The age is "+this.age);
    };

}

var obj1 = new NewPerson("Mark",25,"Male");
alert("The age is as follows "+obj1.getName());

// output: //输出:

The age is 25 The age is as follows undefined 年龄为25岁。未定义年龄如下

因为你没有退货。

You have to explixitly return in you function 你必须彻底回归你的功能

Following should work 以下应该工作

function NewPerson(name, age, sex){
    this.name = name;
    this.age = age;
    this.sex = sex;

    this.getName = function(){
        //alert(this.name);
        alert("The age is "+this.age);
    return this.age
    };

}

    var obj1 = new NewPerson("Mark",25,"Male");
    alert("The age is as follows "+obj1.getName());

No one else mentioned it so I will - it is more efficient to put functions that will be the same for all instances on the constructor's prototype. 没有人提到它所以我会 - 在构造函数的原型上放置对所有实例都相同的函数会更有效。 Then you only have one instance of the function that is used by all instances, eg 然后,您只有一个所有实例使用的函数实例,例如

function NewPerson(name, age, sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
} 

NewPerson.prototype.getName = function() {
    alert("The age is "+this.age);
    return this.name;
}

@Davenewton 's answer is correct and while I like it for its straightforwardness, it takes that @Davenewton的答案是正确的,虽然我喜欢它的直截了当,但需要这样做
famous a-ha! 着名的哈哈! moment for you to fully realize why. 你完全明白为什么的那一刻。 Here's what's really going on: 这是真正发生的事情:

So to elaborate If we had something like this: 所以详细说明如果我们有这样的事情:

 function i_am(){ var a = 'very smart person'; console.log(this.a); } var a = 'monkey'; i_am(); 

Depending on what linter or browser you might be using, this might either return 根据您可能使用的linter或浏览器,这可能会返回

> "monkey" // (try the snippet)

or also 或者也

> "monkey"  
> undefined    // check the sreenshot

在此输入图像描述

This is because of one simple reason, best understood if we go step-by-step how compiler "reads" the code. 这是因为一个简单的原因,如果我们逐步地编译器“读取”代码,那就最好理解了。

  1. hoist the function i_am() declaration to top ( undefined ) function i_am()声明提升到顶部( undefined
  2. hoist the var a declaration to top ( undefined ) var a声明提升到顶部( undefined
  3. assign 'monkey' to variable a (now string "monkey" ) 'monkey'分配给变量a (现在为字符串"monkey"
  4. execute/invoke the i_am() a function we have pre-declared 执行/调用i_am()我们预先声明的函数
  5. create a local variable a and assign string "very smart person" 创建一个局部变量a并指定字符串"very smart person"
  6. console.log(this.a) returns 'monkey' , because this refers to var / property a (same thing in this case) of the global object - call-site is from global object : i_am(); console.log(this.a)返回'monkey' ,因为this引用了global对象的var / property a (在本例中是相同的) - call-site来自global对象: i_am();
  7. Finish execution - but uh oh! 完成执行 - 但是哦哦! We executed function and returned no value! 我们执行了函数并没有返回值!

Now, depending on your environment, either it hides the undefined result from you, or it prints it out! 现在,根据您的环境,它会隐藏您undefined结果,或者将其打印出来! Why? 为什么? Because function s are looking to return a value. 因为function s希望return一个值。 Just like with variable declaration, if you do 就像变量声明一样,如果你这样做的话

 var a; console.log(a); 

it has not been assigned a value, hence it results after RHS in undefined . 它没有被赋值,因此它在undefined RHS之后产生。

Similar principle applies to function, where it's looking to return a value, but it doesn't return anything, hence resulting in undefined 类似的原则适用于函数,它正在寻找返回值,但它不会返回任何内容,因此导致undefined


In other words, it's not this that return s undefined . 换句话说, 它不是thisreturn小号undefined It's the invokation of i_am(); 这是i_am();的调用i_am(); that returns undefined ! 返回undefined

Hopefully it's clear to everybody now :) 希望现在每个人都清楚:)

If you want to get some value from called function you must use 如果你想从被调用的函数中获取一些值,你必须使用

return value;

So try 所以试试吧

function NewPerson(name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;

this.getName = function(){
    alert("The age is "+this.age);
    return this.name;
};
}  
var obj1 = new NewPerson("Mark",25,"Male");
alert("The name is as follows "+obj1.getName());

will work as you expected. 将按预期工作。

As stated before, you didn't return anything in getName . 如前所述,您没有在getName返回任何内容。

It looks like you don't really want to alert age in getName . 看起来你真的不想在getName提醒年龄。 Also, adding getName to each instance of the object in the constructor is inefficient. 此外,将getName添加到构造函数中对象的每个实例都是低效的。 Use the prototype method instead. 请改用原型方法。 I am submitting the cleaned-up code for what you are probably going for: 我正在提交清理代码,以满足您的需求:

    function Person(name, age, sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    };
    Person.prototype.getName = function() {
        return this.name;
    };
    var obj1 = new Person("Mark",25,"Male");
    alert("The name is: "+obj1.getName());

By placing getName on the prototype, all instances of Person will have access to the same function, thus saving memory :) By using the statement this.getName = ... in the constructor function Person, you are making a new function for each instance of Person. 通过在原型上放置getName ,Person的所有实例都可以访问相同的函数,从而节省内存:)通过在构造函数Person中使用语句this.getName = ... ,您将为每个实例创建一个新函数人

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

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