JavaScript学习—原型和继承

来源:互联网 发布:淘宝网免费开店流程 编辑:程序博客网 时间:2024/05/18 23:55

一、原型链

JavaScript创建每个函数都自动添加prototype属性,它是函数的原型。

举例:

function ClassA(){}

ClassA.prototype=new Object();

function ClassB(){}

ClassB.prototype=new ClassA();

function ClassC(){}

ClassC.prototype=new ClassB();

var obj=new ClassC();

alert(obj instanceof ClassC); //true

alert(obj instanceof ClassB); //true

alert(obj instanceof ClassA); //true

alert(obj instanceof Object); //true

二、继承

JavaScript模拟继承方法,四种方法:构造继承法,原型继承法,实例继承法和拷贝继承法。

(1) 构造继承法

var x = function(size){this.size = function(){return size;};}

var y = function(){

var m_elem=[];

m_elem = Array.apply(m_elem,arguments); //调用对象m_elem;对象y的参数arguments赋给数组对象Array

this.z = x; //对象z继承对象x

this.z.call(this,m_elem.length);} //调用对象z(即x的方法和属性),将参数m_elem.length传给对象z(即x的方法和属性)

var a = new y(1,2,3);

alert(a.size());

*call和apply,第一参数是调用的对象,第二个参数是传的参数(call传单个参数,apply传数组)

举例:

function print(text){alert(this.value +' - ' + text+'');}  

var a = {value: 10, print : print};  

print('hello'); //this => global, output "undefined - hello"

a.print('a'); //this => a, output "10 - a"

print.call(a,'a'); //this => a, output "10 - a"

print.apply(a, ['a']); //this => a, output "10 - a"

bind之后this指针不变:

var q = print.bind(a);

q('a');             //this => a, output "10 - a"

var b = {value: 20, print : print};

q.call(b,'b');     //this => a, output "10 - b"

q.apply(b, ['b']);  //this => a, output "10 - b"

(2) 原型继承法

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('+'); //继承对象Cal原型的方法

(3) 实例继承法

var Cal =function(x, y){this.x = x;this.y = y;}

var c =new Cal(4, 5);

alert(c.x);



原创粉丝点击