如何从构造函数参数创建成员? [英] How to create members from constructor arguments?

查看:98
本文介绍了如何从构造函数参数创建成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于构造函数参数创建一些对象成员,但是它没有按预期工作。没有成员被创建。我怎样才能实现这个目标?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆