我是JavaScript的新手,正在学习JavaScript:The Good Parts一书。在该书中,以下配方用于将方法扩展为所有功能:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
我想探索这个概念,所以想出了以下脚本,旨在将greet()
方法添加到func()
函数中:
//define how the augmentation will work
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
}
//create a dummy function to augment
function func() {
//do nothing
}
//create function to be added
func.method('greet', function() {
console.log("Greetings from greet()!");
});
//access the new function
func.greet();
但是,当我运行它时,出现了错误Uncaught TypeError: undefined is not a function
。有人可以告诉我我在做什么错。
在这种情况下,您要修改该行:
this.prototype[name] = func;
只是
this[name] = func;
或者,您可以使用
this.constructor.prototype[name] = func;
但这会将每个新方法添加到每个函数中,而不仅仅是您调用method
的方法。或者您可以使用:
var f2 = new func();
f2.greet();
为什么?
在JavaScript中查找对象的属性时,将搜索对象本身,然后搜索对象prototype
的constructor
of(依此类推)。的.constructor
的func
是Function
。
在这种情况下,如果您写了以下内容,那么您所做的将可以工作:
func.method('greet', function() {
console.log("Greetings from greet()!");
});
var f2 = new func();
f2.greet();
函数的原型用于该函数创建的新实例。(您创建的对象.constructor
本身具有创建功能的一个。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句