第5章 原型
1.创建一个名为shape的对象,并为该对象设置一个type属性和一个getType()方法。
2.定义一个原型为shape的Triangle()构造函数,用Triangle()创建的对象应有三个对象属性—-a、b、c,分别用于表示三角形的三条边。
3.在对象原型中添加一个名为getPerimeter()的新方法。
4.使用下面的代码来测试您之前的实现:
var t = new Triangle(1,2,3);
t.constructor===Triangle;
//true
shape.isPrototypeOf(t);
//true
t.getPerimeter();
//6
t.getType();
//"triangle"
5.用循环遍历对象t,列出其所有的属性和方法(不包括原型部分的)。
1、2、3、4、5题参考答案
首先说一句,作者的编程水平可能比较碉堡,但是数学拙计了吧
var shape={
type:"shape",
getType:function(){
return this.type;
}
};
function Triangle(pa,pb,pc){
this.type="triangle";
this.a=pa;
this.b=pb;
this.c=pc;
}
Triangle.prototype=shape;
Triangle.prototype.getPerimeter=function(){
return this.a+this.b+this.c;
};
Triangle.prototype.constructor=Triangle;
var t = new Triangle(1,2,3);
console.log(t.constructor===Triangle);
console.log(shape.isPrototypeOf(t));
console.log(t.getPerimeter());
console.log(t.getType());
for(var a in t){
if(t.hasOwnProperty(a)){
console.log(a+"---"+t[a]);
}
}
6.实现随机打乱函数shuffle(),执行效果如下:
[1,2,3,4,5,6,7,8,9].shuffle();
//[2,4,1,8,9,5,3,7]
参考答案:
Array.prototype.shuffle=function(){
var temp;
var r;
var i=this.length;
while(i){
r=Math.floor(Math.random()*i--);
temp=this[r];
this[r]=this[i];
this[i]=temp;
}
};