简体   繁体   English

如何在对象构造函数的键值对中包含先前声明的函数作为值?

[英]How do I include a previously declared function as a value in a key-value pair in an object constructor?

The task: 任务:

  1. declare a variable called myName that returns an array of two elements, firstname and last name. 声明一个名为myName的变量,该变量返回一个由两个元素组成的数组,即名字和姓氏。

  2. declare a function called join(), it will return the two elements as a string with a space between each element. 声明一个名为join()的函数,它将以字符串形式返回两个元素,每个元素之间有一个空格。

  3. declare a function createProfile that should expect an array "name" as input(???). 声明一个函数createProfile,该函数应该将数组“名称”作为输入(???)。

  4. createProfile creates and returns an object with two key-value pairs. createProfile创建并返回带有两个键值对的对象。 key: name value: use the function "join()" and the parameter "name" variable to return a string with your full name, separated by a space 键:名称值:使用函数“ join()”和参数“名称”变量返回全名的字符串,并用空格分隔

    key : email value : my email as a string. key :电子邮件value :我的电子邮件(字符串)。

  5. Declare a variable called myProfile and assign the result of calling createProfile with myName. 声明一个名为myProfile的变量,并使用myName分配调用createProfile的结果。

The problem is in step 4. I believe I should use an object constructor. 问题出在步骤4。我相信我应该使用对象构造函数。 I don't know how to properly include the function join() a value in a key-value pair in an object constructor. 我不知道如何在对象构造函数的键值对中正确包含函数join()一个值。

Here is what I have tried so far: 到目前为止,这是我尝试过的:


const myName = ["firstname", "lastname"];

function join(){
    document.write("Hello, my name is " + myName[0] + " " + myName[1] + ".");
};

join();


function createProfile(name, email){
    this.name = function(){
        return this.join();
    };
    this.email = email;
    return this;
}

let myProfile = new createProfile(name,"me@gmail.com");
console.log(myProfile);

Expected results: calling create profile should log an object with my full name as a string, and my email address as a string. 预期结果:调用create profile应该记录一个对象,该对象的我的全名是一个字符串,而我的电子邮件地址是一个字符串。

Actual results: 实际结果:

createProfile {name: ƒ, email: "hotcoffeehero@gmail.com"}
email: "hotcoffeehero@gmail.com"
name: ƒ ()
__proto__: Object

The value of name is an empty function. name的值是一个空函数。

How do I display it as a string? 如何将其显示为字符串?

Onegai Shimasu 温盖岛松

if you want to use your logic, you need fix the code with the next code 如果要使用逻辑,则需要使用下一个代码修复该代码

const myName = ["firstname", "lastname"];

function join(){
    //document.write("Hello, my name is " + myName[0] + " " + myName[1] + ".");
    return myName[0] + ' ' + myName[1] // You only return the values
};

join();


function createProfile(name, email){
    this.name = join(); // you call the function and assing to name
    this.email = email;
    return this;
}

const myProfile = new createProfile(name,"me@gmail.com");
console.log(myProfile);

but there are better ways to development this 但是有更好的方法来发展

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

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