javascript 继承,prototype

  
function SuperType(name) { 
	this.name = name;
    this.property = "super type";
	this.colors = ['red', 'blue', 'green'];
    this.foo = function() {
		console.log("SuperType this.foo");
	}
}
SuperType.prototype.sayName = function () { 
 console.log(this.name);
}
SuperType.prototype.getSuperValue = function () {
	return this.property;
}
SuperType.prototype.foo = function() {
	console.log("SuperType.prototype.foo");
}

function SubType(name, job) { 
	SuperType.call(this, name);
    this.subproperty = "child type";
	// this.foo = function() {console.log("SubType this.foo");}
	this.job = job;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SuperType;
SubType.prototype.sayJob = function() {
	console.log(this.job);
}

SubType.prototype.getSubValue = function () { 
	return this.subproperty;
};
SubType.prototype.foo = function() {
	console.log("SubType.prototype.foo");	
};

var instance = new SubType();
console.log( instance.getSuperValue() );   // super type
console.log( instance.getSubValue() );  // child type
console.log("-------------------");
console.log( instance.foo() );  // SuperType this.foo \n undfined
console.log("-------------------");

var instance1 = new SubType('Jiang', 'student') 
instance1.colors.push('black') 
console.log(instance1.colors) //["red", "blue", "green", "black"] 
instance1.sayName() // 'Jiang' 
instance1.sayJob() // 'student' 

var instance2 = new SubType('Vol\'jin', 'doctor') 
console.log(instance2.colors) // //["red", "blue", "green"] 
instance2.sayName() // Vol'jin
instance2.sayJob() // 'doctor'

console.log("-------------------");
function createAnother(o) { 
 var clone = Object.create(o); /* 创建一个新对象  */
 clone.sayHi = function() { /* 添加方法  */
	console.log("hi");
 } 
 return clone; /* 返回这个对象  */
} 
var instance3 = createAnother(instance);
console.log(instance3.sayHi());  /* hi undefined  */

console.log("-------------------");

// reset inheritance
SubType.prototype = {};

function inheritPrototype(subType, superType) { 
 var proto = Object.create(superType.prototype);  // 创建父类原型的副本
 proto.constructor = subType; // 将创建的副本添加constructor属性
 subType.prototype = proto; // 将子类的原型指向这个副本
}
inheritPrototype(SubType, SuperType);
var instance4 = new SubType('Jiang', 'student');
instance4.sayName();

  

// https://www.jb51.net/article/82587.htm

猜你喜欢

转载自www.cnblogs.com/mingzhanghui/p/9210690.html
今日推荐