本文详细讲述了JavaScript继承的特性与实践应用。分享给大家供大家参考,具体如下:
继承是代码重用的模式。JavaScript 可以模拟基于类的模式,还支持其它更具表现力的模式。但保持简单通常是最好的策略。
JavaScript 是基于原型的语言,也就是说它可以直接继承其他对象。
JavaScript 的原型不是直接让对象从其他对象继承,而是插入一个多余的间接层:通过构造函数来产生对象。
当一个函数被创建时,Function 构造器产生的函数对象会运行这样类似的代码:
this.prototype = {constructor : this};
新的函数对象新增了一个 prototype 属性,它是一个包含了 constructor 属性且属性值为该新函数的对象。
当采用构造器调用模式,即用 new 去调用一个函数时,它会这样执行:
Function.method('new', function (){ var that = Object.create(this.prototype);//创建一个继承了构造器函数的原型对象的新对象 var other = this.apply(that, arguments);//调用构造器函数,绑定 this 到新对象 return (typeof other === 'object' && other) || that;//如果构造器函数的返回值不是对象,就直接返回这个新对象});
我们可以定义一个构造器,然后扩充它的原型:
//定义构造器并扩充原型var Mammal = function (name) { this.name = name;};Mammal.prototype.get_name = function () { return this.name;};Mammal.prototype.says = function () { return this.saying || '';};
然后构造实例:
var myMammal = new Mammal('Herb the mammal');console.log(myMammal.get_name());//Herb the mammal
构造另一个伪类来继承 Mammal(定义构造器函数并替换它的 prototype):
var Cat = function (name) { this.name = name; this.saying = 'meow';};Cat.prototype = new Mammal();
扩充原型:
Cat.prototype.purr = function (n) { var i, s = ''; for (i = 0; i < n; i += 1) { if (s) { s += '-'; } s += 'r'; } return s;};Cat.prototype.get_name = function () { return this.says() + ' ' + this.name + ' ' + this.says();};var myCat = new Cat('Henrietta');console.log(myCat.says());//meowconsole.log(myCat.purr(5));//r-r-r-r-rconsole.log(myCat.get_name());//meow Henrietta meow
我们使用 method 方法定义了 inherits 方法,来隐藏上面这些丑陋的细节:
/** * 为 Function.prototype 新增 method 方法 * @param name 方法名称 * @param func 函数 * @returns {Function} */Function.prototype.method = function (name, func) { if (!this.prototype[name])//没有该方法时,才添加 this.prototype[name] = func; return this;};Function.method('inherits', function (Parent) { this.prototype = new Parent(); return this;});
新闻热点
疑难解答
图片精选