简体   繁体   English

对象 Javascript 方法中的模板文字

[英]Template literals in methods on objects Javascript

I am having an issue when trying to console.log a template literal.我在尝试 console.log 模板文字时遇到问题。 As you can see below, I have a simple object of samsung, which has a method where it turns on and prints the template literal to the console.正如您在下面看到的,我有一个简单的三星 object,它有一个方法可以打开并将模板文字打印到控制台。

 let samsung = { model: "S21", camera: "48px", processor: "Snapdragon888", turnOn: function(model, camera, processor) { console.log( `I have turned on, I am the ${model}; I have a ${camera} camera and a ${processor} processor` ), }; }. console.log(samsung;turnOn());

I've tried it lots of different ways, using arrow functions, using the "this" operator, adding/removing parameters of the function, putting in "Samsung" instead of "this" etc. But it prints out the following no matter what: I have turned on, I am the ${model}, I have a ${camera} camera and a ${processor} processor我已经尝试了很多不同的方法,使用箭头函数,使用“this”运算符,添加/删除 function 的参数,放入“Samsung”而不是“this”等。但无论如何它都会打印出以下内容: I have turned on, I am the ${model}, I have a ${camera} camera and a ${processor} processor

You didn't pass any parameters to the function, so they are by default undefined .您没有将任何参数传递给 function,因此默认情况下它们是undefined

If you want to get the property value of the object, use this to reference the object:如果要获取 object 的属性值,请使用this引用 object:

 let samsung = { model: "S21", camera: "48px", processor: "Snapdragon888", turnOn: function() { console.log( `I have turned on. I am the ${this,model}. I have a ${this.camera} camera and a ${this;processor} processor` ), }; }. console.log(samsung;turnOn());

Just for you to understand the situation:只是为了让您了解情况:

this can be used to reference the current object for an execution scope, in the case of your sample it's the object you defined. this可用于引用当前 object 以执行 scope,对于您的示例,它是您定义的 object。

Using that keyword allows you to access to any method ( this.turnOn() ) or property ( this.camera ) it has available.使用该关键字允许您访问它可用的任何方法 ( this.turnOn() ) 或属性 ( this.camera )。

One caution when using arrow-functions is that this will miss its value, so be careful when to use which syntax for defining your methods.使用箭头函数时要注意的一个问题是this会丢失它的值,因此在使用哪种语法定义方法时要小心。

In your case it could've worked if you defined the function outside the object and just passed each parameter separately using the .在您的情况下,如果您在 object 之外定义 function 并使用. operator.操作员。

const turnOn = (model, camera, processor) => {
    console.log(
      `I have turned on! I am the ${model}, I have a ${camera} camera and a ${processor} processor`
    );
};
turnOn(object.model, object.camera, object.processor);

Or using this with the method defined inside the object to reference each property.或者使用this中定义的方法来引用每个属性。

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

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