虽然我在jQuery和JavaScript方面有一些工作经验,但我仍然觉得很难理解原型继承。因此,我开始阅读斯托扬·斯特凡诺夫的书“面向对象的JavaScript”。然而,在解决书中的下列练习时,我遇到了一些问题:
shape的对象,该对象具有type属性和getType方法。Triangle构造函数。用Triangle创建的对象应该有三个自己的属性:a、b和c,它们代表三角形的两边。getPerimeter的原型中。使用以下代码测试您的实现:
var t = new Triangle(1, 2, 3);
t.constructor; // Triangle(a, b, c)
shape.isPrototypeOf(t); // true
t.getPerimeter(); // 6
t.getType(); // "triangle"我试图用以下代码解决这个问题:
shape = {
type : "",
getType: function(){
return this.type;
}
};
function Triangle(a, b, c) {
}
Triangle.prototype = shape;然而,它似乎不像预期的那样起作用。你将如何解决这个问题?请详细解释一下。我真的很想了解原型继承。
发布于 2013-08-28 17:43:26
在传递给构造函数的params中,您不会做任何事情,可能假设它们只是分配给新创建的对象。问题是他们不是。
你应该写这样的东西..。
var shape = {
type: '',
getType: function() { return this.type; }
};
function Triangle(a, b, c) {
this.type = 'triangle';
this.a = a;
this.b = b;
this.c = c;
}
Triangle.prototype = shape;
Triangle.prototype.getPerimeter = function() {
return this.a + this.b + this.c;
};
Triangle.prototype.constructor = Triangle;要点(为什么constructor是为prototype定义的)非常简单:每个Triangle对象都应该知道它的构造函数,但是对于Triangle的每个实例,这个属性是相同的。这就是为什么把它放在Triangle.prototype上的原因。
发布于 2013-08-28 17:46:38
像这样的东西会有用的:
function Shape() {
this.type = "shape";
this.getType = function(){
return this.type;
}
}
function Triangle(a,b,c){
this.type="triangle";
this.a =a;
this.b = b;
this.c = c;
}
var shape = new Shape(); //follow the requirements a bit more literally :)
Triangle.prototype = shape;
Triangle.prototype.getPerimeter = function() {
return this.a + this.b + this.c;
}弹琴示例:http://jsfiddle.net/TbR6q/1
切记,这是一个coffeescript非常好的领域,可以让您变得更加清晰和简洁。这相当于“咖啡记录”。
class Shape
constructor: ->
@type = "shape"
getType : -> @type
class Triangle extends Shape
constructor: (@a,@b,@c) ->
@type="triangle"
getPerimeter: () -> @a + @b + @chttp://jsfiddle.net/qGtmX/
发布于 2013-08-28 18:49:09
你走在正确的轨道上。你的代码是正确的。只需再添加几行代码:
shape = {
type : "",
getType: function () {
return this.type;
}
};
function Triangle(a, b, c) {
this.type = "triangle";
this.a = a;
this.b = b;
this.c = c;
}
Triangle.prototype = shape;
shape.getPerimeter = function () {
return this.a + this.b + this.c;
};为了了解正在发生的事情,我建议你阅读以下答案:
https://stackoverflow.com/questions/18494653
复制相似问题