/*
* js prototype exploration prototype
*/
var a = { f:1 } var a2 = Object.create(a);// a2 gets the properties of object a through the create method and then through the prototype chain.//It can be said that this It is a simple object inheriting a2 inheriting a a2.f1 = 2; //Generally, if the subclass does not exist, it will look up along the prototype chain until it finds the topmost Object. If the prototype does not exist, return to the undefind console. log(a2.hasOwnProperty("f")); //Model class in js
//Parent class
function Parent(val){ this.a = val; } //Subclass //js prototype inheritance method one /* * Use call or apply to carry out this point to force conversion */ function Students(name){ Parent.call(this,name)//here this refers to Student inherits in this way } var s = new Students("haha"); // console.log(sa); //prototype inheritance of js Method 2 /* * Copy the instance of student through the prototype chain prototype of the child parent class. First find the attribute a on the prototype of the student. If it does not exist, it will look up along the copied parent chain */ function Students(){}
Students.prototype = new Parent("hehe");
var s = new Students();
//console.log(sa);
//The underlying code of Object.create also uses method two
function create2(obj){ function F (){}; F.prototype = obj;//The instance is equivalent to inheriting the stuff from grandpa obj return new F(); }