JavaScript学习—原型和继承

一、原型链

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);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值