直接访问字符串方法

Direct access to String Method

本文关键字:方法 字符串 访问      更新时间:2023-09-26

众所周知,像concat(),indexof()这样的字符串方法可以通过String.prototype获得。因此,每当创建新的字符串对象时,它都可以使用这些方法。但是在这里我发现的是字符串,javascript对象本身可以访问这些方法,即不一定需要新的字符串对象。String 构造函数如何访问 String.prototype 中存在的方法?

工作规范:

<script type="text/javascript">
         var str3 = String.concat( "hlw","Stackover" );
         document.write("Concatenated String :" + str3); //outputs:hlwstackoverflow
</script>

这里的链接显示了 abv 方法的工作原理:请记住用 abv 替换代码http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_76

最后,我使用的浏览器是火狐

Javascript 中的所有内容(或几乎所有内容)都被视为对象。

假设我们正在创建 String 对象

// First I will define a constructor
function String(text) {
   this.text = text;
   this.indexOf = function() { ... };
}

在Javascript中,构造函数也是一个对象实例。当我在构造函数中使用"this"关键字时,我告诉我想在所有称为原型的javascript对象中存在的特殊对象中创建一个新属性。

// Then I add a new property without using prototype obj
String.concat = function(txt1,txt2) { ... };
alert(String.prototype.indexOf); // it works
alert(String.concat);          // it works
                                // It will work because I'm using the String main Object

当您从 Myclass Obj 创建新实例时。新创建的对象将从父对象继承原型对象,但不会继承直接添加到 MyClass obj 的属性:

var instance = new String("any text");
alert(instance.concat); // undefined because the new instance will
                     // inherit only what is inside prototype obj

我必须将其添加到原型对象中才能使新实例继承该属性;

String.prototype.concat = function(txt1,txt2) { ... };
var instance = new String("any text");
alert(instance.concat) // it works

我猜一些库在你调用它之前直接在你的 String 对象中添加了一个 concat 函数。

编辑:

在Firefox,Chrome,Internet Explorer和Safari上进行了测试。你的代码在火狐上工作。所以,我猜FIREFOX,在你调用之前的某个地方,直接向String Obj添加一个concat(txt1,txt2,...)。但这根本不是默认行为。

只需先启动一个字符串对象,然后像这样连接:

var str = "string1"
var constr = str.concat("string2");

在您的情况下:

var str1 = "hlw";
var str2 = "Stackover";
document.write("Concatenated String :" + str1.concat(str2));

这是一个小提琴

您可以直接从原型调用此方法,如下所示:

String.prototype.concat("hlw","Stackover");

没有方法String.concat,但如果定义了"字符串"变量,则可能会发生这种情况

var String = "";
String.concat("hlw","Stackover")

但是

Firefox 中的所有标准内置对象似乎都是如此,例如Array.indexOf

(当我们知道您假设的当前环境时,更容易知道会发生什么)

顺便说一句,这些方法似乎不一样:

String.concat.length // 2
String.prototype.concat.length // 1

并且String.concat方法不依赖于String.prototype.concat

String.prototype.concat = null;
String.concat("foo","bar") // foobar