实现一个Person和他的子类Student, Person要求有一个私有变量age和共有变量name,同时拥有一个共有方法getAge。Student继承Person,并且拥有一个共有方法readBook。并给出如下两行的输出结果:
console.log(oneStudent instanceof Person); console.log(oneStudent instanceof Student);
我的实现:
function Person(){var age = 15; this.name = 'one Person'; this.getAge = function(){ return age; }}var onePerson = new Person();console.log(onePerson.name);console.log(onePerson.getAge());
function Student(){ this.readBook = function(){ console.log('i am reading.'); }}Student.prototype = new Person();
var oneStudent = new Student();oneStudent.name ='one student';oneStudent.readBook();
console.log(oneStudent.name);console.log(oneStudent instanceof Person); //trueconsole.log(oneStudent instanceof Student);//true
console.log(onePerson instanceof Student);//false
总结:oneStudent instanceof Person 的值是true,可以通过这个特性,实现面向接口的编程,从而实现灵活扩展。