js的原型、this与继承
先看一个例子
function Person(name,age){ this.name=name; this.age = age; } Person.prototype.getName=function(){ return this.name; } var person = new Person("zhangsan",123); alert(Person.getName());
Person.prototype在person原型上加入一个getName方法用来返回对象的name属性。通过对象.prototype添加的相当于Java中的public 方法。当然也可以通过
Person.函数直接在Person上添加方法,这相当于Java中的static方法。在原型上添加的方法必须创建对象才能调用该方法。
其中this.name起到了Java中public的作用。如果去掉this则会为undefined。在javascript中this功能十分强大,下面js继承还需要用到。在js中this代表当前对象,但是比Java中的this灵活。看下面例子
function TestThis(name){ this.name=name; return name; } window.TestThis("window this"); function Student(){} Student.aa=TestThis; alert(Student.aa("student this"));
可以看出第一次this代表的document对象,第二次代表的是Student对象。
js的继承,js的继承不想Java那么灵活。js的继承有四种方法。本次最简单的一个方法。通过调用call方法即可实现。
function Person(name){ this.name=name; this.show=function(){ return this.name; } } function Teacher(){ Person.call(this,"123"); this.getUpper=function(){ return this.show(); } } var teacher = new Teacher(); alert(teacher.getUpper());
Person.call(this,"123")相当于把Person对象中的属性方法添加到当前对象上。
浙公网安备 33010602011771号