javascript中的作用域和上下文使用简要概述(3)


MyClass.prototype.init = function(){
// call the superclass init method in the context of the "MyClass" instance
MySuperClass.prototype.init.apply(this, arguments);
}


通过在子类(MyClass)的实例中调用超类(MySuperClass)的方法,我们能重现这种强大的设计模式。

结论

在你开始学习高级设计模式之前理解这些概念是非常重要的,由于作用域和上下文在现代javascript中扮演重要的和根本的角色。无论我们谈论闭包,面向对象,和继承或各种原生实现,上下文和作用域都扮演重要角色。如果你的目标是掌握javascript语言并深入了解它的组成,作用域和上下文应该是你的起点。

译者补充

作者实现的bind函数是不完全的,调用bind返回的函数时不能传递参数,下面的代码修复了这个问题:

复制代码 代码如下:


if(!(‘bind' in Function.prototype)){
Function.prototype.bind = function(){
var fn = this, context = arguments[0], args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, args.concat(arguments));//fixed
}
}
}

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdwjxx.html