2把共享的属性方法移动到prototype上

来源:互联网 发布:淘宝店身份认证复核 编辑:程序博客网 时间:2024/06/05 11:23

demo:http://runjs.cn/code/1bum1jxc    

写在前面:在前一章基础上继续修改,红色标注为不同之处

//构造函数    function Shape() {};    //添加原型    Shape.prototype.name = "Shape";    Shape.prototype.toString = function() {        return this.name;    }    //其他构造函数    function TwoDshape() {};    //继承原型链属性    TwoDshape.prototype = new Shape();    //修改constructor指向    TwoDshape.prototype.constructor = TwoDshape;    //修改TwoDshape的属性    TwoDshape.prototype.name = "2d shape";    //第三个构造函数,和其他函数不一样的是这里有自身自带的方法属性    function Triangle(side, height) {        this.side = side;        this.height = height;    }    //继承原型链属性,再次签到必须在拓展原型对象属性前完成继承关系的构建    Triangle.prototype = new TwoDshape();    Triangle.prototype.constructor = Triangle;//A    //修改属性    Triangle.prototype.name = "Triangle";    Triangle.prototype.getArea = function() {        return this.side * this.height / 2;    }    //开始试验----------    var my = new Triangle(5, 10);    console.log("和上一章已经进行相同的检测")    var my = new Triangle(5, 10);    console.log(my.toString());    //my的构造函数是谁呢?    console.log("my的构造函数是谁呢?---------");    console.log(my.constructor === Triangle); //在A处我们明确把Triangle的constructor指向了Triangle    console.log("通过instanceof来主动查找实例my对象的构造函数是谁?");    console.log(my instanceof Shape); //true    console.log(my instanceof TwoDshape); //true    console.log(my instanceof Triangle); //true    console.log("通过构造函数sPrototypeOf方法来判断是否拥有相应的实例------------")    console.log(Shape.prototype.isPrototypeOf(my)); //true    console.log(TwoDshape.prototype.isPrototypeOf(my)); //true    console.log(Triangle.prototype.isPrototypeOf(my)); //true    console.log("效果和上一章一模一样,下面来的不一样的,通过hasOvenProperty()来验证是自身属性还是原型链属性")    console.log(my.hasOwnProperty('side')) //true    console.log(my.hasOwnProperty('name')) //false


0 0
原创粉丝点击