使用';这';在函数原型中-JavaScript

使用';这';在函数原型中-JavaScript,javascript,Javascript,我试图理解一些我并不经常使用的JavaScript原型概念。这里我有两个相同的方法,一个用于数组,另一个用于函数。一个有效,另一个无效。你能解释一下这里的区别吗 var arr = ['test']; var string = 'test'; Array.prototype.print = function(){ console.log(this); } Function.prototype.print = function () { console.log(t

我试图理解一些我并不经常使用的JavaScript原型概念。这里我有两个相同的方法,一个用于数组,另一个用于函数。一个有效,另一个无效。你能解释一下这里的区别吗

var arr = ['test'];
var string = 'test';

Array.prototype.print = function(){
        console.log(this);
}
Function.prototype.print = function () {
        console.log(this);
}

arr.print(); // logs the arr with value 'test'
string.print(); //logs string.print is not a function

您正在“扩展”函数
prototype
,但在
字符串上调用
print
函数

将代码更改为:

String.prototype.print = function () {
        console.log(this);
}
String.prototype.print = function () {
        console.log(this);
}

它会工作。

错误表明代码中存在问题,没有在字符串原型上定义打印函数,而是在根本没有使用的函数上定义了打印函数

String.prototype.print = function () {
//^^^^^--
        console.log(this);
}
var-arr=['test'];
变量字符串='test';
Array.prototype.print=函数(){
console.log(this);
}
String.prototype.print=函数(){
console.log(this);
}
arr.print();//使用值“test”记录arr

string.print()//logs string.print不是一个函数
第一个函数有效,因为您做得对。您将
print
函数添加到
Array

第二个不起作用,因为你做错了。您需要将
print
函数添加到
String

String.prototype.print = function () {
    console.log(this);
}

字符串继承字符串,您可以向字符串原型添加打印方法,如下所示:


如果您试图扩展函数原型并访问字符串原型,请使用缩写…

。您误解了原型继承的概念

var arr = ['test'];
var string = 'test';
var someMethod = function(){ /* some code */ };

Array.prototype.print = function(){
        console.log(this);
}

String.prototype.print = function () {
        console.log(this);
}

//Extending the prototype of Function
Function.prototype.print = function () {
        console.log(this);
}


arr.print(); // logs the arr with value 'test'
string.print(); //logs string.print is not a function
someMethod.print(); // this will trigger the print method
// extended in Function Prototype.
更新

非常有趣的一点是,我意识到这篇文章是用Javascript写的。它是 您可以将函数原型视为其他原型。想象你是 扩展函数本身的函数(似乎是 (开始时)。所以有一些有趣的方法,比如
call,apply,
绑定
。因此,我们甚至可以扩展函数的功能。如果我错了,请纠正我 在我能想到的任何其他语言中,扩展函数似乎 这是不可能的。考虑到我们没有特权接触 该语言的源代码。JS中非常强大的功能


Function.prototype.print
=>
String.prototype.print
字符串不是函数的实例,因此它们不会从Function.prototype继承@RacilHilan,但最终您将在字符串原型中添加一个新方法。字符串也是JS中的基本数据类型。此打印将可用于数据类型为字符串的所有变量。我在其他语言中没有见过这种行为,比如在原始数据类型中扩展方法。你能举个例子吗
var arr = ['test'];
var string = 'test';
var someMethod = function(){ /* some code */ };

Array.prototype.print = function(){
        console.log(this);
}

String.prototype.print = function () {
        console.log(this);
}

//Extending the prototype of Function
Function.prototype.print = function () {
        console.log(this);
}


arr.print(); // logs the arr with value 'test'
string.print(); //logs string.print is not a function
someMethod.print(); // this will trigger the print method
// extended in Function Prototype.