javascript Object继承#js #object #inherit

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Object继承#js #object #inherit相关的知识,希望对你有一定的参考价值。

if(typeof Object.create!='function'){
		Object.create = function(o){
			var F = function(){};
			F.prototype = o;
			return new F();
		}
	}
var o = Object.create(a)





/**********/

function inheritPrototype(subType,superType){
	// 两个参数:子类型构造函数和超类型构造函数

	var prototype = object(superType.prototype);
	// 创建超类型原型的副本

	prototype.constructor = subType;
	// 为副本添加constructor属性,弥补重写原型失去默认constructor属性

	subType.prototype = prototype;
	// 创建的新对象赋值给子类型的原型
}





/*********/


function extend(base, sub) {

  var origProto = sub.prototype;
  sub.prototype = Object.create(base.prototype);
  for (var key in origProto)  {
     sub.prototype[key] = origProto[key];
  }
  // Remember the constructor property was set wrong, let's fix it
  sub.prototype.constructor = sub;
  // In ECMAScript5+ (all modern browsers), you can make the constructor property
  // non-enumerable if you define it like this instead
  Object.defineProperty(sub.prototype, 'constructor', { 
    enumerable: false, 
    value: sub 
  });
}

// Let's try this
function Animal(name) {
  this.name = name;
}

Animal.prototype = {
  sayMyName: function() {
    console.log(this.getWordsToSay() + " " + this.name);
  },
  getWordsToSay: function() {
    // Abstract
  }
}

function Dog(name) {
  // Call the parent's constructor
  Animal.call(this, name);
}

Dog.prototype = {
    getWordsToSay: function(){
      return "Ruff Ruff";
    }
}    

// Setup the prototype chain the right way
extend(Animal, Dog);

// Here is where the Dog (and Animal) constructors are called
var dog = new Dog("Lassie");
dog.sayMyName(); // Outputs Ruff Ruff Lassie
console.log(dog instanceof Animal); // true
console.log(dog.constructor); // Dog

以上是关于javascript Object继承#js #object #inherit的主要内容,如果未能解决你的问题,请参考以下文章

经典面试题:js继承方式下

JavaScript非构造函数的继承( object()方法浅拷贝与深拷贝 )

JavaScript对象原型继承

JavaScript之原型式继承&寄生式继承和寄生组合式继承以及优缺点

JS继承 实现方式

js属性扩展,继承,属性查找