那么,我们能不能把这些东西封装起来呢,我们需要使用 prototype。看下面的示例:
- var Cal = function(x, y){
- this.x = x;
- this.y = y;
- }
-
- Cal.prototype.operations = {
- '+': function(x, y) { return x+y;},
- '-': function(x, y) { return x-y;}
- };
-
- Cal.prototype.calculate = function(operation){
- return this.operations[operation](this.x, this.y);
- };
-
- var c = new Cal(4, 5);
-
- c.calculate('+');
- c.calculate('-');
这就是 prototype 的用法,prototype 是 javascript 这个语言中最重要的内容。网上有太多的文章介始这个东西了。说白了,prototype 就是对一对象进行扩展,其特点在于通过“复制”一个已经存在的实例来返回新的实例,而不是新建实例。被复制的实例就是我们所称的“原型”,这个原型是可定制的(当然,这里没有真正的复制,实际只是委托)。上面的这个例子中,我们扩展了实例 Cal,让其有了一个 operations 的属性和一个 calculate 的方法。
这样,我们可以通过这一特性来实现继承。还记得我们最最前面的那个 Person 吧, 下面的示例是创建一个 Student 来继承 Person。
- function Person(name, email, website){
- this.name = name;
- this.email = email;
- this.website = website;
- };
-
- Person.prototype.sayHello = function(){
- var hello = "Hello, I am "+ this.name + ", <br>" +
- "my email is: " + this.email + ", <br>" +
- "my website is: " + this.website;
- return hello;
- };
-
- function Student(name, email, website, no, dept){
- var proto = Object.getPrototypeOf;
- proto(Student.prototype).constructor.call(this, name, email, website);
- this.no = no;
- this.dept = dept;
- }
-
- // 继承prototype
- Student.prototype = Object.create(Person.prototype);
-
- //重置构造函数
- StudentStudent.prototype.constructor = Student;
-
- //重载sayHello()
- Student.prototype.sayHello = function(){
- var proto = Object.getPrototypeOf;
- var hello = proto(Student.prototype).sayHello.call(this) + '<br>';
- hello += "my student no is: " + this. no + ", <br>" +
- "my departent is: " + this. dept;
- return hello;
- };
-
- var me = new Student(
- "Chen Hao",
- "haoel@hotmail.com",
- "http://coolshell.cn",
- "12345678",
- "Computer Science"
- );
- document.write(me.sayHello());
|