我试图理解一些我不经常使用的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
,但在String
上调用print
函数。
将您的代码更改为:
String.prototype.print = function () {
console.log(this);
}
它将工作。
错误说明了代码中的问题,您未在字符串原型上定义打印函数,而是在您根本不使用的函数上进行的。
String.prototype.print = function () {
//^^^^^--
console.log(this);
}
var arr = ['test'];
var string = 'test';
Array.prototype.print = function() {
console.log(this);
}
String.prototype.print = function() {
console.log(this);
}
arr.print(); // logs the arr with value 'test'
string.print(); //logs string.print is not a function
第一个作品是因为您做对了。您将print
函数添加到Array
。
第二个不起作用,因为您做错了。您需要将print
功能添加到String
:
String.prototype.print = function () {
console.log(this);
}
字符串继承字符串,您可以将打印方法添加到字符串原型:
String.prototype.print = function () {
console.log(this);
}
[Array,Function,String,Object].forEach(n=>n.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.
update
我在JavaScript中意识到这篇文章非常有趣。这是 您可以将功能原型视为其他原型。想象你是 扩展功能本身的功能(似乎是一个 善意(。因此,有有趣的方法,例如
call, apply , bind
。因此,我们可以扩展函数的功能。如果我错了,请纠正我 在我能想到的任何其他语言中,似乎扩展功能似乎 不可能。鉴于我们没有特权触摸 该语言的源代码。JS中非常有力的功能