recently, I have been looking at Boss Ruan"s object inheritance, Javascript object-oriented programming (2): inheritance of constructors
, but I ran the code myself and found several problems. I don"t know what"s wrong. Three problems:
1, constructor apply
//object
function logObj(obj) {
console.log("new OBJECT LOG-------------------------------");
for(var prop in obj) {
console.log(`${prop} == ${obj[prop]}`);
}
}
function Person(name, sex) {
this.name = name;
this.sex = sex;
this.fav = "read";
}
Person.prototype.say = function() { //
console.log(`I"m ${this.name},and my sex is ${this.sex}`);
}
function People(name,sex,nation){
Person.apply(this,arguments);
this.nation = nation;
}
var me = new People("li","man","China");
console.log(me);
me.say();//
apply constructor inheritance mode, cannot get person"s say common method.
2, another inheritance method,
function People(nation) {
this.nation = nation;
}
People.prototype = new Person();
console.log(People.prototype.constructor);
People.prototype.constructor = People;
var me = new People("China");
logObj(me);
you can get properties and public methods by inheriting the parent class instance, but the parent class property is undefined. How to modify the properties of the parent class in the constructor parameters of the subclass instance, for example, can name, be modified only through me.name
3, directly inheriting the prototype
function extend(Child, Parent) {
var F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function People(nation) {
this.nation = nation;
}
extend(People, Person);
var he = new People("China");
logObj(he);
console.log(he.name);//undefined
console.log(he.fav); //undefined
found that this inheritance method can get the common method say, but cannot inherit the properties name and sex,fav of the parent Class.
it feels like everything is wrong, and there is a copy inheritance behind it. Errors are reported when adding new attributes, indicating that there is no such thing on the prototype chain.
//
var Chinese = {
nation: "",
fav: "read"
};
var Doctor = {
career: ""
}
function deepCopy(p, c) {
var c = c || {};
for(var i in p) {
if(typeof p[i] === "object") {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
var Doctor = deepCopy(Chinese);
Chinese.birthPlaces = ["", "", ""];
Doctor.birthPlaces.push(""); //
logObj(Chinese);
logObj(Doctor);