Javascript学习笔记–类的继承

最近在看天雪发给我看的一本Javascript的书,是JQuery之父写的,写得很棒,里面推荐的资源也很棒。为了弥补我的差记性,特写下学习笔记。

http://javascript.crockford.com/inheritance.html
这个是讲Js里面的类继承的写法,这个作者太犯贱了,上面的例子都是用自己写的方法,结果方法在最下面才写出来,告诉我们。搞得我一开始以为是内置的方法呢。。。不过他的方法写得太酷了,下面列举一下:

Sugar(作者管他写的方法叫做糖,确实很甜)

To make the examples above work, I wrote four sugar methods. First, the method method, which adds an instance method to a class.
为了上面的例子跑起来,我写了四个很甜的方法。首先,是method方法,它是用来把方法添加到class里的。

This adds a public method to the Function.prototype, so all functions get it by Class Augmentation. It takes a name and a function, and adds them to a function’s prototype object.

It returns this. When I write a method that doesn’t need to return a value, I usually have it return this. It allows for a cascade-style of programming.

Next comes the inherits method, which indicates that one class inherits from another. It should be called after both classes are defined, but before the inheriting class’s methods are added.

Again, we augment Function. We make an instance of the parent class and use it as the new prototype. We also correct the constructor field, and we add the uber method to the prototype as well.

The uber method looks for the named method in its own prototype. This is the function to invoke in the case of Parasitic Inheritance or Object Augmentation. If we are doing Classical Inheritance, then we need to find the function in the parent‘s prototype. The return statement uses the function’s apply method to invoke the function, explicitly setting this and passing an array of parameters. The parameters (if any) are obtained from the arguments array. Unfortunately, the arguments array is not a true array, so we have to use apply again to invoke the array slice method.

Finally, the swiss method.

The swiss method loops through the arguments. For each name, it copies a member from the parent‘s prototype to the new class’s prototype.

才翻译了一个,发现懒得翻译了。。。实在是个懒人啊。。。大家将就着看,我什么时候想到了再来翻译一下好了,其实都是很简单的英语。

1 comment

  1. 我快啃完英文了,表示:这个作者真是……最后才写出来,让我以为是内置的……

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">