1.原型链实例

来源:互联网 发布:淘宝客服公司图片 编辑:程序博客网 时间:2024/06/06 07:14

//构造函数------------    function Shape() {        this.name = "Shape";        this.toString = function() {            return this.name;        }    }    //构造函数------------    function TwoShape() {        this.name = "2D shape";    }    //构造函数------------    function Triangle(side, height) {        this.name = "Triangle";        this.side = side;        this.height = height;        this.getArea = function() {            return this.side * this.height / 2;        }    }    //这里通过new对象来实现赋值的所以不会对原来对象有任何影响,        //!!必须在拓展原型对象属性前完成继承关系的构建,否则会被覆盖    TwoShape.prototype = new Shape();    Triangle.prototype = new TwoShape();    //修改对象constructor的指向    TwoShape.prototype.constructor = TwoShape;    Triangle.prototype.constructor = Triangle;//A.    //开始测试,尽管Triangle本身并没有toString方法,    //但是通过继承获取到了相应的toStrig方法,同时这里的this指向实例后的my    var my = new Triangle(5, 10);    console.log(my.toString());       console.log(my.side);    //my的构造函数是谁呢?    console.log("my的构造函数是谁呢?---------");    console.log(my.constructor ===Triangle);//在A处我们明确把Triangle的constructor指向了Triangle      console.log("通过instanceof来主动查找实例my对象的构造函数是谁?");   console.log(my instanceof Triangle);//true   console.log(my instanceof TwoShape);//true   console.log(my instanceof Triangle);//true   console.log("通过构造函数sPrototypeOf方法来判断是否拥有相应的实例------------")   console.log(Shape.prototype.isPrototypeOf(my));//trueconsole.log(TwoShape.prototype.isPrototypeOf(my));//trueconsole.log(Triangle.prototype.isPrototypeOf(my));//true

实例效果:http://runjs.cn/code/eh8zpcs8


1 0
原创粉丝点击