[英]Using 'this' in a function prototype - JavaScript
我试图理解一些我不经常使用的JavaScript原型概念。 这里我有两个相同的方法,一个用于Array,另一个用于Function。 一个工作,另一个不工作。 你能解释一下这有什么区别吗?
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
您正在“扩展”Function prototype
但在String
上调用print
函数。
将您的代码更改为:
String.prototype.print = function () {
console.log(this);
}
它会起作用。
错误说明你的代码中的问题,你没有在String原型上定义打印功能,而是在你没有使用的功能上做了。
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
第一个是有效的,因为你做得对。 您向Array
添加了print
函数。
第二个不起作用,因为你做错了。 您需要向String
添加print
函数:
String.prototype.print = function () {
console.log(this);
}
string inherit String,你可以将print方法添加到String原型中,如下所示:
String.prototype.print = function () {
console.log(this);
}
[Array,Function,String,Object].forEach(n=>n.prototype.print=function(){
console.log(this);
});
一个简短的......
如果您正在尝试扩展函数原型并访问String原型。 你是对原型继承概念的误解
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 , bind
。 所以我们可以扩展甚至功能的功能。 如果我错了,请纠正我,不像我能想到的任何其他语言,扩展功能似乎是不可能的。 鉴于我们没有权利触摸该语言的源代码。 JS中非常强大的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.