我们常常会提到继承,说实在的,这种多态的形式只属于典型的面向对象语言的,那么,在我们说的js语言下,也会有么,当然。我们来看看
我们常常会让一个构造函数继承另一个构造函数,eg:
function A(){ this.a = 1; } function B(){ A.call(this); this.b = 2; } B.prototype = Object.create(A.prototype); //注意,这里使用的Object.create 而不是直接赋值于A.prototype,若是直接赋值A.prototype的话,下面对B.prototype的操作将会影响到A.prototype B.prototype.constructor = B; //这两句相当于 B.prototype = new A();使用这种方式将会继承父类的实例及原型 ...
继承父类构造函数及原型eg:fcuntion A(){this.a = 1} A.prototype.m(a){ this.a += a; return 'prototype is A'; } function B(){A.call(this)} // this.temp = A;this.temp() 继承父类实例(调用父类构造方法) B.prototype = Object.create(A.prototype) // 继承父类原型在这里B.prototype.constructor 指向的是A B.prototype.constructor = B; // 修改B的构造函数指向 var b = new B(); b.a // 1 b.m(2) // "prototype is A" b.a // 3 b instanceof A // true b instanceof B // true
继承单个方法可以使用如下方式eg:A = function(){ this.a = function(){ return 1; } } A.prototype.m = function(){ return 'prototype is A'; } B = function(){} B.prototype.m = function(){ A.prototype.m.call(this) } B.prototype = Object.create(A.prototype); B.prototype.constructor = B var b = new B() b.a // undefined b.m() // "prototype is A"
在其他的服务端语言,我们会经常提到多继承,子类继承多个父类的情况,但是js中却没有类似的,但是我们可以通过其他的方法来实现这种功能eg:
function A(){
this.a = 1;
}
function B(){
this.b = 2;
}
function C(){
A.call(this);
B.call(this);
};
C.prototype = Object.create(A.prototype);
Object.assign(C.prototype,B.prototype); // es6中方法assign合并对象,将多个父类的prototype合并到C.prototype
C.prototype.constructor = C;
var c = new C();
c.a // 1
c.b // 2
封装私有变量:
1、通过构造函数来达到封装私有变量的目的
function A(){
var arr = []; // 私有变量,只有实例能访问到
this.push = function(str){
arr.push(str);
}
}
var a = new A()
arr // undefined; arr只在函数A内部有效
2、将私有变量放在实例对象上
function A(){
this._arr = [];
}
A.prototype = {
constructor:A,
add:function(parm){
this._arr.push(parm)
},
getArr:function(){
return this._arr;
}
}
3、通过立即执行函数
var A = (function(){
var _a = 0;
var m = function(){
...
};
return {
m:m
}
})();//这种方式又跟闭包类似,当然可以封装私有变量
A._a // undefined
当其自执行函数后面传递参数,则该参数自在该自执行函数内部有效,eg:
var A = (function(m){
return m;
})(window.m || {})
其模块化也是这种方式 如jQuery等
js中的面向对象:等您坐沙发呢!