Dieser Artikel stellt Ihnen die neue Methode Object.create() in ECMAScript 5 vor. Für diejenigen, die es nicht wissen, können Sie gerne sammeln und lernen~
ECMAScript 5 hat Object.create( ) code>-Methode standardisiert das Konzept der prototypischen Vererbung [Empfohlenes Lernen: <a href="https://www.php.cn/course/list/17.html" target="_blank">JavaScript-Video-Tutorial a> 】<code>Object.create()
方法将原型式继承的概念规范化【推荐学习:JavaScript视频教程】
用法
var obj = Object.create({name: 'johan', age: 23}) // obj 继承了属性name 和 age var obj2 = Object.create(null) // obj2 不继承任何属性和方法 var obj3 = Object.create(Object.prototype) // 与 {} 和 new Object() 一个意思 var obj4 = Object.create({}, { property1: { value: true, writable: true } }) // 第二个参数与 Object.defineProperties() 一致 图解 Object.create 实现 function create(proto) { function F(){} F.prototype = proto return new F() }
第一步: function F(){}
即创建一个函数,因为约定首字母大写,视为构造函数,创建函数 F 时,F 构造函数与和它的原型对象就有了这一层的关系:
F.prototype === F.prototype; // 假设你把F.prototype当作一个值 F.prototype.constructor === F;
第二步:F.prototype = proto
即将 F.prototype 赋值为传入的 proto,如此就打破了F.prototype = F.prototype 以及 F.prototype.constructor = F ,它们的关系为
第三步:return new F()
var obj = Object.create({name: 'johan'})
function F(){}
Das heißt, dass der erste Buchstabe per Konvention großgeschrieben wird. Es wird als Konstruktor betrachtet. Wenn die Funktion F verwendet wird, hat der F-Konstruktor diese Beziehung zu seinem Prototypobjekt: Object.create(null)
Schritt 2: F.prototype = proto
F.prototype Zuweisen Wert für die übergeben proto , wodurch F.prototype = F.prototype und F.prototype.constructor = F gebrochen werden. Ihre Beziehung ist
Maybe You still don' Ich verstehe den dritten Schritt nicht ganz. Lassen Sie uns ihn mit Beispielen kombinieren und es wird auf einen Blick klar sein } Was F.prototype = {name: 'johan'} betrifft, wurde es nach dem Aufruf von Object.create von der Engine als Garbage Collection erfasst, da niemand die F-Funktion verwendete, sodass es zu obj.__proto__ = {name: 'johan' wurde. }
Auf diese Weise wurde die „prototypische Vererbung“ weitergegeben
🎜Das Prinzip ist folgendes: Einfach ausgedrückt besteht es darin, eine leere (Konstruktor-)Funktion zu erstellen und ihren Prototyp zuzuordnen (Implementierungsvererbung)🎜var obj = Object.create(null)
Das obige ist der detaillierte Inhalt vonIllustration der Object.create-Methode in js (mit Codebeispiel). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!