简体   繁体   English

在javascript中定义对象方法

[英]Define object method in javascript

I want to make my custom object in javascript. 我想在javascript中创建自定义对象。 I have made a method in my object to make value uppercase but it is not working. 我在我的对象中创建了一个方法,使值大写,但它不起作用。 fiddle 小提琴

function mystring (name,uppercase){
this.name= name;
this.uppercase= function (){
return this.toUpperCase();
};

}
var jj= new mystring('mycompany');
 jj=jj.uppercase();
console.log(jj)

You need to do 你需要这样做

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);

You forgot the this.name in the this.uppercase function 你忘了this.uppercase函数中的this.name

You are trying to convert to the entire object to upper case, if you check the console it tells you that the element has no method toUpperCase . 您正在尝试将整个对象转换为大写,如果您检查控制台,它会告诉您该元素没有方法toUpperCase Instead convert the string, not the object. 而是转换字符串,而不是对象。

return this.name.toUpperCase();

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

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