function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello, I am ' + this.name);
};
function Child() {
this.name = 'Child';
}
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 输出:Hello, I am Child
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello, I am ' + this.name);
};
function Child(name) {
Parent.call(this, name);
}
var child = new Child('Child');
child.sayHello(); // 输出:Hello, I am Child
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log('Hello, I am ' + this.name);
};
function Child(name) {
Parent.call(this, name);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child('Child');
child.sayHello(); // 输出:Hello, I am Child
function createObject(proto) {
function F() {}
F.prototype = proto;
return new F();
}
var parent = {
name: 'Parent',
sayHello: function() {
console.log('Hello, I am ' + this.name);
}
};
var child = createObject(parent);
child.name = 'Child';
child.sayHello(); // 输出:Hello, I am Child
function createObject(proto) {
function F() {}
F.prototype = proto;
return new F();
}
function Child(name) {
var child = createObject(parent);
child.name = name;
child.sayHello = function() {
console.log('Hello, I am ' + this.name);
};
return child;
}
var parent = {
name: 'Parent',
sayHello: function() {
console.log('Hello, I am ' + this.name);
}
};
var child = Child('Child');
child.sayHello(); // 输出:Hello, I am Child