prototype.js中的class.create()方法

来源:互联网 发布:淘宝司法拍卖车靠谱吗 编辑:程序博客网 时间:2024/06/06 21:39

Class.create

Class.create([superclass][, methods...]) → Class
  • superclass (Class) – The optional superclass to inherit methods from.
  • methods (Object) – An object whose properties will be "mixed-in" to the new class. Any number of mixins can be added; later mixins take precedence.

Class.create creates a class and returns a constructor function for instances of the class. Calling the constructor function (typically as part of a new statement) will invoke the class's initialize method.

Class.create accepts two kinds of arguments. If the first argument is a Class, it's used as the new class's superclass, and all its methods are inherited. Otherwise, any arguments passed are treated as objects, and their methods are copied over ("mixed in") as instance methods of the new class. In cases of method name overlap, later arguments take precedence over earlier arguments.

If a subclass overrides an instance method declared in a superclass, the subclass's method can still access the original method. To do so, declare the subclass's method as normal, but insert $super as the first argument. This makes $super available as a method for use within the function.

To extend a class after it has been defined, use Class#addMethods.

For details, see the inheritance tutorial on the Prototype website.



链接:http://www.prototypejs.org/api



小demo:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var Animal = Class.create();
Animal.prototype = {
  initialize: function(name, sound) {
    this.name  = name;
    this.sound = sound;
  },
  speak: function() {
    alert(name + " says: " + sound + "!");
  }
};
var snake = new Animal("Ringneck""hissssssssss");
snake.speak();
// -> alerts "Ringneck says: hissssssssss!"
var Dog = Class.create();
Dog.prototype = Object.extend(new Animal(), {
  initialize: function(name) {
    this.name  = name;
    this.sound = "woof";
  }  
});
 
 
var fido = new Dog("Fido");
fido.speak();
 
// -> alerts "Fido says: woof!"



原创粉丝点击