JavaScript:返回对象的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12272239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: function returning an object
提问by BrainLikeADullPencil
I'm taking some JavaScript/jQuery lessons at codecademy.com. Normally the lessons provide answers or hints, but for this one it doesn't give any help and I'm a little confused by the instructions.
我正在 codecademy.com 上一些 JavaScript/jQuery 课程。通常课程会提供答案或提示,但对于这一课,它没有提供任何帮助,而且我对这些说明感到有些困惑。
It says to make the function makeGamePlayer return an object with three keys.
它说让函数 makeGamePlayer 返回一个带有三个键的对象。
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
}
I'm not sure if i should be doing this
我不确定我是否应该这样做
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
}
or something like this
或类似的东西
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = {
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
}
}
I have to be able to modify the properties of the object after its created.
我必须能够在创建对象后修改对象的属性。
回答by Oriol
In JavaScript, most functionsare both callable and instantiable: they have both a [[Call]]and [[Construct]]internal methods.
在 JavaScript 中,大多数函数既可调用又可实例化:它们都有[[Call]]和[[Construct]]内部方法。
As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.
作为可调用对象,您可以使用括号来调用它们,可以选择传递一些参数。作为调用的结果,该函数可以返回一个值。
var player = makeGamePlayer("John Smith", 15, 3);
The code above calls function makeGamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
上面的代码调用函数makeGamePlayer
并将返回值存储在变量中player
。在这种情况下,您可能希望像这样定义函数:
function makeGamePlayer(name, totalScore, gamesPlayed) {
// Define desired object
var obj = {
name: name,
totalScore: totalScore,
gamesPlayed: gamesPlayed
};
// Return it
return obj;
}
Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this
inside the function. In the case above, since makeGamePlayer
is not called as a method, the this
value will be the global object in sloppy mode, or undefined in strict mode.
此外,当你调用一个函数时,你也在底层传递了一个额外的参数,它决定this
了函数内部的值。在上面的情况下,由于makeGamePlayer
不是作为方法调用,因此this
在 sloppy 模式下该值将是全局对象,或者在严格模式下是 undefined。
As constructors, you can use the new
operatorto instantiate them. This operator uses the [[Construct]]internal method (only available in constructors), which does something like this:
作为构造函数,您可以使用new
运算符来实例化它们。该运算符使用[[Construct]]内部方法(仅在构造函数中可用),它执行如下操作:
- Creates a new object which inherits from the
.prototype
of the constructor - Calls the constructor passing this object as the
this
value - It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
- 创建一个继承自
.prototype
构造函数的新对象 - 调用构造函数将此对象作为
this
值传递 - 如果它是一个对象,则它返回构造函数返回的值,否则返回在步骤 1 中创建的对象。
var player = new GamePlayer("John Smith", 15, 3);
The code above creates an instance of GamePlayer
and stores the returned value in the variable player
. In this case, you may want to define the function like this:
上面的代码创建了一个 的实例GamePlayer
并将返回值存储在变量中player
。在这种情况下,您可能希望像这样定义函数:
function GamePlayer(name,totalScore,gamesPlayed) {
// `this` is the instance which is currently being created
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
// No need to return, but you can use `return this;` if you want
}
By convention, constructor names begin with an uppercase letter.
按照惯例,构造函数名称以大写字母开头。
The advantage of using constructors is that the instances inherit from GamePlayer.prototype
. Then, you can define properties there and make them available in all instances
使用构造函数的优点是实例继承自GamePlayer.prototype
. 然后,您可以在那里定义属性并使它们在所有实例中可用
回答by PeeHaa
You can simply do it like this with an object literal:
您可以简单地使用对象字面量这样做:
function makeGamePlayer(name,totalScore,gamesPlayed) {
return {
name: name,
totalscore: totalScore,
gamesPlayed: gamesPlayed
};
}
回答by Jeremy J Starcher
Both styles, with a touch of tweaking, would work.
两种风格,稍加调整,都会起作用。
The first method uses a Javascript Constructor, which like most things has pros and cons.
第一种方法使用 Javascript 构造函数,它与大多数事物一样有利有弊。
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
另一方面,如果我没记错的话,您的另一种方法称为“揭示闭合模式”。
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
回答by Rob
The latest way to do this with ES2016 JavaScript
使用 ES2016 JavaScript 执行此操作的最新方法
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
回答by scrappedcola
I would take those directions to mean:
我认为这些方向的意思是:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}