1.2扩展Object的prototype实现继承
function Parent(){}
②定义一个子类
function Son(){}
③通过prototype给object类添加一个扩展方法(通过for-in循环,将父类的属性和方法赋给子类)
Object.prototype.extend = function(parent){ for(var i in parent){ this[i] = parent[i]; } }
④分别拿到父类对象,和子类对象
var p = new Person(); var s = new Student();
⑤用子类对象,调用扩展方法,实现继承操作
s.extend(p);
完整代码如下:
// 1.定义父类 function Person(name,age){ this.name = name; this.age = age; this.say = function(){ alert(this.name+":"+this.age); } } // 2.定义子类 function Student(no){ this.no = no; this.add = function(a,b){ alert(a+b); } } function Programmer(lang){ this.lang = lang; this.codding = function(){ alert("我在读书!"); } } // 3.通过原型给Object对象添加一个扩展方法。 Object.prototype.customExtend = function(parObj){ for(var i in parObj){ // 通过for-in循环,把父类的所有属性方法,赋值给自己 this[i] = parObj[i]; } } var p = new Person("张三","18"); var s = new Student("0001"); s.customExtend(p);//现在s继承了p的所有属性和方法。
完整代码
①无法通过一次实例化,直接拿到完整的子类对象。而需要先拿到父类对象和子类对象两个对象,再手动合并;
②扩展object的继承方法,也会保留在子类对象上。
1.3通过原型实现继承
function Parent(){}
②定义一个子类
function Student(){}
③将父类对象,赋值给子类的prototype
Son.prototype = new Person();
④拿到子类对象,就会将父类对象的所有属性和方法,添加到__proto__
var s = new Son()
完整代码如下:
function Person(name,age){ this.name = name; this.age = age; this.say = function(){ alert("我叫:"+this.name+";今年:"+this.age+"岁"); } } function Student(no){ this.no = no; } Student.prototype=new Person("jh",14); //子类prototype指向父类对象 var stu = new Student(12); stu.say();//继承后,子类获得了父类的全部属性方法
完整代码
①子类自身的所有属性都是成员属性;父类继承过来的属性都是原型属性。
②依然无法通过一步实例化拿到完成的子类对象。
1.4使用call和apply和bind实现继承
①定义一个父类
funtion Parent(){}
②定义子类时,在子类使用三个函数,调用父类,将父类函数的this,指向为子类函数的this
function Son(no,name){
this.no = no;
Person.call(this,name);
}
③实例化子类时,将自动继承父类属性
var s = new Son(12,"zhangsan");
function Person(name,age){ this.name = name; this.age = age; this.say = function(){ alert("我叫:"+this.name+";今年:"+this.age+"岁"); } } function Student(no,stuName,stuAge){ this.no = no; Person.call(this,stuName,stuAge); // 执行上述代码,相当于把Person类所有this替换为Student类this // 换言之,也就是把Person类所有属性和方法,全给了Student类 } var stu = new Student(12,"zhangsan",14); stu.say();// 子类继承了父类say方法
完整代码
好了!今天就给大家分享一下JavaScript面向对象中的继承~~如果有什么疑问,欢迎大家多多留言~~
:http://www.linuxidc.com/Linux/2017-11/148244.htm