如何从构造函数参数创建成员? [英] How to create members from constructor arguments?
问题描述
我想基于构造函数参数创建一些对象成员,但是它没有按预期工作。没有成员被创建。我怎样才能实现这个目标?
I want to create some object members based on a constructor argument, but it's not working as expected. No members are created. How can I achieve this?
function Foo(parameters = []) {
parameters.forEach(function(e) {
this[e.name] = e.initial;
});
};
const p = [{
"name": "sensitivity",
"initial": 50
}];
const f = new Foo(p);
推荐答案
您正在使用此
forEach
方法提供的回调功能中的关键字,但此
该函数只是窗口对象的引用。
You are using this
keyword within the callback function provided by forEach
method, but the this
of that function is just a reference to the window object.
您可以阅读有关范围的更多信息这个回答中的
。
You can read more about the scope of this
in javascript in this answer.
bind()方法创建一个新函数,当调用时,将其
这个关键字设置为提供的值,并在调用新函数时提供给定的
参数序列。
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function Foo(parameters = []) {
parameters.forEach(function(e) {
this[e.name] = e.initial;
}.bind(this));
};
const p = [{
"name": "sensitivity",
"initial": 50
}];
const f = new Foo(p);
console.log(f);
直到箭头
函数,每个新
功能定义了自己的此
值。
Until arrow
functions, every new
function defined its own this
value.
例如,这个
在构造函数的情况下可以是一个新对象。
For instance, this
can be a new object in the case of a constructor.
function Person(age){
this.age=age;
console.log(this);
}
let person=new Person(22);
或此
如果创建的函数可以指向到 base
对象可以像 obj.getAge()
一样访问。
Or this
can points to the base
object if the function created can be accessed like obj.getAge()
.
let obj={
getAge:function(){
console.log(this);
return 22;
}
}
console.log(obj.getAge());
一个箭头
函数不会创建自己的这个
,它只是用这个
的值
执行 context
。另一方面, arrow
函数使用这个
的父范围。
An arrow
function does not create its own this
, it's just used the this
value of the enclosing
execution context
. In the other hand, arrow
function uses this
of parent scope.
function Foo(parameters = []) {
parameters.forEach((e) => {
this[e.name] = e.initial;
});
};
const p = [{
"name": "sensitivity",
"initial": 50
}];
const f = new Foo(p);
console.log(f);
这篇关于如何从构造函数参数创建成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!