返回它在Javascript中构建的新对象

Return new object it built in Javascript

本文关键字:新对象 对象 构建 Javascript 返回      更新时间:2023-09-26

我正在练习Javascript对象函数。假设我有firstNamelastName作为函数的两个自变量。我想像这样显示{"firstName":"tim","lastName":doe}。这是我的代码,但打印出来时没有定义。知道吗?非常感谢。

function myFunction(firstName, lastName) {
  this.name1 = firstName;
  this.name2 = lastName;
}
var obj = new myFunction();
console.log(myFunction('tim', 'doe'));

试试这个:

console.log(new myFunction('tim', 'doe'));

或者这个:

console.log(obj);

你可以试试这个

function myFunction(firstName, lastName) {
  this.name1 = firstName;
  this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);

您可以查看此文档JavaScript Constructors

这种函数称为构造函数,不应该直接调用它。您必须将其与new一起使用。

console.log(new myFunction('tim', 'doe'));

这将按您的期望打印结果。

为了区分构造函数和普通函数,最好以大写字母开头命名,如下所示:

function MyFunction(...) {...}

您收到的未定义来自没有返回值的函数,请参阅这篇文章:简单函数返回';未定义';值

为了得到你想要的结果。。。

function myFunction(firstName, lastName) {
    this.name1 = firstName;
    this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);

让我们探究一下这一行的作用:console.log(myFunction('tim', 'doe'));

此部分:myFunction('tim', 'doe')将myFunction作为一个函数执行。由于myFunction没有返回运算符,它的返回值是"undefined",这是javascript表示它不存在的方式。因此,控制台上会打印"未定义"一词。

其他提示:尝试添加此行:console.log(typeof myFunction);

这应该打印"函数"。(愿"typeof"操作员成为你最好的朋友)

尝试添加一个返回行作为myFunction的最后一行,例如:

return 'First name: ' + firstName + " Last name: " + lastName;

但是,此时"var obj=new myFunction();"行未使用。

尝试添加另一行:console.log(typeof obj);

这应该打印"object",这意味着"obj"只是一个对象。

这里有一个完整的例子,你可以玩:

function myFunction(firstName, lastName) {
  this.name1 = firstName;
  this.name2 = lastName;
  this.getNames = function() {
      return 'First name: ' + firstName + " Last name: " + lastName;
  }
  console.log("This executes once upon instatiation (the line with var obj = new ...)");
  return "Return value";
}
var obj = new myFunction('tim', 'doe');
console.log(typeof myFunction);
console.log(typeof obj);
console.log(obj.getNames());

如果以上任何一项需要澄清,请告诉我。祝你好运

顺便说一句,控制台上的输出应该是这样的:

This executes once upon instatiation (the line with var obj = new ...)
script.js:14 function
script.js:15 object
script.js:16 First name: tim Last name: doe