在 JavaScript 中定义对象方法

Define object method in javascript

本文关键字:对象 方法 定义 JavaScript      更新时间:2023-09-26

我想用javascript制作我的自定义对象。我已经在我的对象中创建了一个使值大写的方法,但它不起作用。小提琴

function mystring (name,uppercase){
this.name= name;
this.uppercase= function (){
return this.toUpperCase();
};
}
var jj= new mystring('mycompany');
 jj=jj.uppercase();
console.log(jj)

你需要做

function mystring (name,uppercase){
    this.name= name;
    this.uppercase= function (){
        return this.name.toUpperCase();
    };
}
var jj= new mystring('mycompany');
jj=jj.uppercase();
console.log(jj);

您忘记了this.uppercase函数中的this.name

您正在尝试将整个对象转换为大写,如果您检查控制台,它会告诉您该元素没有方法toUpperCase。而是转换字符串,而不是对象。

return this.name.toUpperCase();