javascript - 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);
解决方案
您可以通过将函数分配给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();
推荐阅读
- django - Django 自定义 ModelManagers 隐式限制每个用户可用的查询集
- java - 想将 FXML 导入为场景,然后使用 FXML 中的相机
- vue.js - 如何在 vue/nuxt 项目中导入和使用 Fontello
- java - 使用 Java 在 Google Analytics 上进行分页
- javascript - Python继续接收来自Javascript的点击事件输出
- xcode - 切换 Flutter 的 Xcode 版本
- python - 为什么 Selenium driver.find 命令返回的列表是应有的两倍大?
- java - 如何关闭 JMS 连接并阻止它监听?
- scala - Flyway 似乎无法识别 java/scala 迁移
- c - C - 如何读取由逗号和空格分隔的输入