标签:show 函数 .sh hello 构造 eof targe 修改 传参
JavaScript 继承问题
继承的发展史
传统形式 ----> 原型链
无法实现多继承,js本身没有多继承机制,但是可以进行代码模拟多继承。
function Star () {
this.person = function(){
console.log("金城武");
}
this.country = function(){
console.log("台湾")
}
this.msg = "this is Star"
}
function Detail(){
this.msg = "this is Detail"
}
Detail.prototype = new Star();
var detail = new Detail();
detail.person();
console.log(detail.msg); //this i Detail
console.log(detail.constructor); //f Star(){······}
console.log( detail instanceof Detail);//true
console.log( detail instanceof Star);//true
借用构造函数(call/apply)
function Basic(name,age){
this.name = name;
this.age = age;
this.dispaly = function(){
console.log(" this is dispaly from Basic");
}
this.dispaly2 = function(){
console.log(" hello world");
}
}
function Gender(gender){
this.gender = gender;
}
// Basic.prototype.dispaly2 = function(){
// console.log(" 我的原型链上的东西");
// }
function Person(name, age, gender){
Basic.call(this,name,age);
Gender.call(this,gender);
this.show = function(){
console.log(this.name,this.age,this.gender);
}
}
var per = new Person("jack", 99, "female");
per.show();
per.dispaly();
per.dispaly2();
共享原型
不能随便改变自己的原型,一但修改全部改,之級改变原型那么父級也将随之改变。
function Father(){
}
Father.prototype.lastName = "Sun";
function Son(){
}
var father= new Father();
Son.prototype = Father.prototype;
var son = new Son();
console.log(son.lastName); //Sun
Son.prototype.lastName = " Wang";
console.log(son.lastName); //Wang
console.log(father.lastName);//Wang
圣杯模式
可以防止原型链上的修改影响到父級。因为有了一个中间对象F出现,所以Target在原型上所作的修改,只会影响F上的属性,真正的父級不会产生影响,但是查找的话是沿着原型链_proto_查找的,可以找到父級,实现继承。
//第一种
var inherit = (function(){
var F = function(){};
return function(Target, Origin){
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}())
//第二种
function inherit (Target, Orgin){
var F = function(){}; //生成一个中间对象,
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
标签:show 函数 .sh hello 构造 eof targe 修改 传参
原文地址:https://www.cnblogs.com/lakemonster/p/9744871.html