简体   繁体   English

JavaScript:如何访问String对象的字符串值?

[英]JavaScript: How can I access the string value of a String object?

I am trying to extend a method to the String prototype . 我正在尝试将方法扩展到String 原型

I want this method to manipulate the string value but I am not sure how do access it. 我想要此方法来操纵字符串值,但是我不确定如何访问它。

this the current object context seems to refer to the string object, but not the actual string value. this当前对象上下文似乎是指String对象,但不是实际的字符串值。

String.prototype.test = function() { console.log(this)}
function () { console.log(this) }
'lol'.test()
 VM192:2 String {0: "l", 1: "o", 2: "l", length: 3, 
 has: function, contains: function, 
 escapeRegExp: function, camelize: function…
}

How do I access the string value instead of the string object? 如何访问字符串值而不是字符串对象?

You need call toString() 您需要调用toString()

String.prototype.test = function() { 
    console.log(this.toString())
}

只需调用toString方法:

console.log( this.toString() )

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

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