您的位置:首页 > Web前端 > JavaScript

js继承

2016-04-15 08:20 811 查看
当一个函数对象被创建时,Function构造器产生的函数对象会运行类似这样的一段代码

this.prototype = {constructor:this};


constructor属性没什么用,重要的是prototype对象.

当采用构造器调用模式,即用
new
去调用一个函数时,函数执行方式会被修改.

Function.method("new",function(){
//创建一个新对象,它继承构造函数的原型对象
var that = Object.create(this.prototype);
//调用构造器函数,绑定this到新对象
var other = this.apply(this, arguments);
//如果他的返回值不是一个对象,就返回该新对象
return (typeof other === "object" && other) || that;
})


1.构造函数绑定

第一种方法也是最简单的方法,使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行:

function Parent(name, age){
this.name = name;
this.age = age;
}
Parent.prototype.getName = function(){
console.log(this.name);
}

function Child(name,age){
Parent.apply(this, arguments);
}
var child = new Child("foo", 7);


优点:创建对象的时候,可以传递参数到父亲对象

缺点:没有继承prototype原型链上的属性

2.prototype

2.1基于对象的继承

在一个纯粹的原型模式中,我们会摒弃类,转而专注对象.基于原型的继承相比基于类的继承在概念上更为简单:一个新对象可以继承一个旧对象的属性.

Object.create = function(obj){
function F(){}
F.prototype = obj;
return new F();
}


//我们先构建一个有用的对象
var myParent = {
name : "the parent",
get_name: function(){
return this.name;
}
}

var myChild = Object.create(myParent);
myChild.name = "the child";
myChild.get_name();


原生式继承总结(道格拉斯总结):

1.没有像类(Class-Like)一样的构造函数(Constructor)(英文原文:no class-like constructors).

2.对象和对象之间直接通过原型实现继承(而不像其他语言中的类和类之间的继承)(英文原文:objects inherits from objects)。

2.2prototype继承构造函数实例化对象

Function.method("inherits", function(Perent){
this.prototype = new Parent();
return this;
});


function Parent(name, age){
this.name = name;
this.age = age;
}
Parent.prototype.getName = function(){
console.log(this.name);
}
function Child(){}
Child.prototype = new Parent("the parent", 23);
//任何一个构造函数的prototype对象都有一个constructor属性,指向它的构造函数
Child.prototype.constructor = Child;
var child = new Child();
child instanceof Child


2.3prototype直接继承构造函数的prototype

将一些属性直接写入prototype,在继承的时候可以直接继承
Parent.prototype


function inherit(ctor, superCtor){
ctor.prototype = superCtor.prototype;
};
//Child.prototype和Parent.prototype公用一个对象
//对Child.prototype的任何修改也会影响Parent.prototype


function Parent(){};
Parent.prototype.name = "the parent";
Parent.prototype.get_name = function(){
console.log(this.name);
}
function Child(){};
Child.prototype = Parent.prototype;
Child.prototype.constructor = Child;
var child = new Child();


nodejs中使用的继承

//util.js
exports.inherits = function(ctor, superCtor) {
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};
//
exports._extend = function(origin, add) {
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
//继承eventEmitter
const util = require("util")
const EventEmitter = require("event");
function MyEmitter(){
EventEmitter.call(this);
}
//MyEmitter和EventEmitter都是构造函数
util.inherits(MyEmitter, EventEmitter);
const myEmitter = new MyEmitter();


参照

Javascript面向对象编程(二):构造函数的继承

老生常谈–Js继承小结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: