首页 > 解决方案 > JavaScript 对象中的方法

问题描述

// Given the object:
var employee = {
  name: "John Smith",
  job: "Programmer",
  age: 31,
  
  }
}

// Add a method called nameLength that prints out the
// length of the employees name to the console.

我正在制作一种方法,但没有得到名称的长度

nameLength: function(){
    console.log(this.name.length);

标签: javascriptobjectthis

解决方案


您可以通过将函数分配给nameLength对象上命名的属性来做到这一点:

var employee = { name: "John Smith", job: "Programmer", age: 31 };
employee.nameLength = function() {
  console.log(this.name.length);
};

employee.nameLength();

您也可以在定义对象时添加它:

var employee = {
  name: "John Smith",
  job: "Programmer",
  age: 31,
  nameLength: function() {
    console.log(this.name.length);
  },
};

employee.nameLength();


推荐阅读