需要了解什么是寄生式继承。
我参考了这个链接:JavaScript中的寄生式继承
我需要理解这个例子的作用:
Shape = {name: 'Shape'};
Shape.prototype.toString = function()
{
return this.name;
};
function Rectangle(width, height) {
var rect;
P = function() {};
P.prototype = Shape;
rect = new P();
rect.width = width;
rect.height = height;
return rect;
}
第二个例子可以正常工作,但我需要知道“寄生继承是在什么情况下出现的?”
var Person = function(name, age)
{
this.name = name;
this.age = age;
};
var Employee = function(name, age, group)
{
var e = new Person(name, age);
e.group = group;
return e;
};
var testname= new Employee('ABC', 30, 'Developer');
谢谢。
P = function() {};
需要加上var
- 否则会变成全局变量。 - kapaShape.prototype.toString
不起作用,因为prototype
属性只有函数,而在你的示例中定义Shape
的是一个使用字面对象语法定义的对象。 - Łukasz Szewczak