uTools-Manuals/docs/javascript/Differential_inheritance_in_JavaScript.html
2019-04-21 11:50:48 +08:00

46 lines
1.9 KiB
HTML

<article id="wikiArticle">
<h2 id="简介">简介</h2>
<p>差异化继承是基于原型编程的一个常见模型,它讲的是大部分的对象是从其他更一般的对象中派生而来的的,只是在一些很小的地方进行了修改。每个对象维护一个指向它们的 <code>prototype</code> 的引用和一个差异化属性列表。</p>
<h2 id="示例">示例</h2>
<p>下面的代码为“继承”一个对象提供了简单的方法:</p>
<pre><code class="language-javascript">Object.prototype.clone = function(){
// 创建一个新的对象,并用 this 作为它的原型
var p = Object.create(this);
/* 并不是必须的:
// 在新对象上应用构造函数
this.constructor.apply(p, arguments);
*/
return p;
};
</code></pre>
<p>使用 <code>继承</code>, 它可以简便的从通用原型中派生出特殊对象。下面的例子使用了 <code>clone</code> 和差异化继承来建立不断增长的个性化对象。</p>
<pre><code class="language-javascript">var root = {}; // Could be any object with any prototype object
var record = root.clone();
record.toString = function(){ return "a Record"; };
var person = root.clone();
person.firstName = false;
person.lastName = false;
person.toString = function(){
return this.firstName ?
(this.lastName ?
this.firstName + " " +this.lastName :
this.firstName) :
(this.lastName ?
this.lastName :
"a Person");
};
JoePerson = person.clone();
JoePerson.firstName = "Joe";
alert( JoePerson.toString() );
</code></pre>
<h2 id="相关链接">相关链接</h2>
<ul>
<li><a href="/en/JavaScript/Reference/Global_Objects/Object/create" title="create">Object.create</a></li>
<li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">inheritance and the prototype chain</a></li>
</ul>
</article>