当前位置:网站首页>Interviewer asked: Inheritance of JS
Interviewer asked: Inheritance of JS
2022-06-28 01:28:00 【InfoQ】
JSnew、call、apply、this、 Inherit Interviewer asks series ReactextendsReact.Component// Part of the source code
function Component(props, context, updater) {
// ...
}
Component.prototype.setState = function(partialState, callback){
// ...
}
const React = {
Component,
// ...
}
// Use
class index extends React.Component{
// ...
}
JSES6classConstructors 、 The relationship between prototype objects and instances
function F(){}
var f = new F();
// Constructors
F.prototype.constructor === F; // true
F.__proto__ === Function.prototype; // true
Function.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true
// example
f.__proto__ === F.prototype; // true
F.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true

ES6 extends
What does inheritance do
ES6// ES6
class Parent{
constructor(name){
this.name = name;
}
static sayHello(){
console.log('hello');
}
sayName(){
console.log('my name is ' + this.name);
return this.name;
}
}
class Child extends Parent{
constructor(name, age){
super(name);
this.age = age;
}
sayAge(){
console.log('my age is ' + this.age);
return this.age;
}
}
let parent = new Parent('Parent');
let child = new Child('Child', 18);
console.log('parent: ', parent); // parent: Parent {name: "Parent"}
Parent.sayHello(); // hello
parent.sayName(); // my name is Parent
console.log('child: ', child); // child: Child {name: "Child", age: 18}
Child.sayHello(); // hello
child.sayName(); // my name is Child
child.sayAge(); // my age is 18
// 1、 Constructor prototype chain
Child.__proto__ === Parent; // true
Parent.__proto__ === Function.prototype; // true
Function.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true
// 2、 Instance prototype chain
child.__proto__ === Child.prototype; // true
Child.prototype.__proto__ === Parent.prototype; // true
Parent.prototype.__proto__ === Object.prototype; // true
Object.prototype.__proto__ === null; // true

ES6 extends- Subclass constructor (
Child) The prototype of the (__proto__) Points to the parent constructor (Parent),
- Subclass instances
childPrototype object (Child.prototype) The prototype of the (__proto__) Points to the parent classparentPrototype object (Parent.prototype).
- Subclass constructor
ChildInherits the parent constructorParentProperties in . UsesuperCalled (ES5Then usecallperhapsapplyCall parameters ). That is, the two lines marked with different colors in the figure .
6.3 Inherit 2 and 3 Smaller The first 1 Smaller 1 and 2 Smaller __proto____proto__new
、
Object.create
and
Object.setPrototypeOf
You can set
__proto__
__proto__newnewprototypenewnew
What did you do :
- A new object is created .
- This object will be executed
[[Prototype]]( That is to say__proto__) link .
- The generated new object is bound to the function call
this.
- adopt
newEach object created will eventually be[[Prototype]]Linked to this functionprototypeOn the object .
- If the function does not return an object type
Object( containFunctoin,Array,Date,RegExg,Error), thatnewThe function call in the expression automatically returns the new object .
Object.create
ES5 Provided
Object.create(proto, [propertiesObject])undefinedES5MDNployfill// A short edition : It is also the application of new Will be set __proto__ The principle of linking .
if(typeof Object.create !== 'function'){
Object.create = function(proto){
function F() {}
F.prototype = proto;
return new F();
}
}
Object.setPrototypeOf
ES6 Provided
Object.setPrototypeOfMDNObject.setPrototypeOf()[[Prototype]]nullObject.setPrototypeOf(obj, prototype)`ployfill`
// Only applicable to Chrome and FireFox, stay IE Not working in :
Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
nodejsfunction inherits(ctor, superCtor) {
if (ctor === undefined || ctor === null)
throw new ERR_INVALID_ARG_TYPE('ctor', 'Function', ctor);
if (superCtor === undefined || superCtor === null)
throw new ERR_INVALID_ARG_TYPE('superCtor', 'Function', superCtor);
if (superCtor.prototype === undefined) {
throw new ERR_INVALID_ARG_TYPE('superCtor.prototype',
'Object', superCtor.prototype);
}
Object.defineProperty(ctor, 'super_', {
value: superCtor,
writable: true,
configurable: true
});
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
}
ES6
Of
extends
Of
ES5
Version implementation
ES6 extends__proto__ES6ES5// ES5 Realization ES6 extends Example
function Parent(name){
this.name = name;
}
Parent.sayHello = function(){
console.log('hello');
}
Parent.prototype.sayName = function(){
console.log('my name is ' + this.name);
return this.name;
}
function Child(name, age){
// amount to super
Parent.call(this, name);
this.age = age;
}
// new
function object(){
function F() {}
F.prototype = proto;
return new F();
}
function _inherits(Child, Parent){
// Object.create
Child.prototype = Object.create(Parent.prototype);
// __proto__
// Child.prototype.__proto__ = Parent.prototype;
Child.prototype.constructor = Child;
// ES6
// Object.setPrototypeOf(Child, Parent);
// __proto__
Child.__proto__ = Parent;
}
_inherits(Child, Parent);
Child.prototype.sayAge = function(){
console.log('my age is ' + this.age);
return this.age;
}
var parent = new Parent('Parent');
var child = new Child('Child', 18);
console.log('parent: ', parent); // parent: Parent {name: "Parent"}
Parent.sayHello(); // hello
parent.sayName(); // my name is Parent
console.log('child: ', child); // child: Child {name: "Child", age: 18}
Child.sayHello(); // hello
child.sayName(); // my name is Child
child.sayAge(); // my age is 18
ES6 Example babeljsES5// The converted code is briefly commented
"use strict";
// It mainly supports the current environment Symbol And don't support Symbol Of typeof Handle
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
// _possibleConstructorReturn Judge Parent.call(this, name) Function return value Is it null Or functions or objects .
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
// how self yes void 0 (undefined) False report
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
// obtain __proto__
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
// The core of parasitic combinatorial inheritance
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
// Object.create() Method creates a new object , Using an existing object to provide a newly created object __proto__.
// That is to say, after implementation subClass.prototype.__proto__ === superClass.prototype; This sentence is true
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
// Set up __proto__
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
// instanceof The operator contains a pair of Symbol To deal with
function _instanceof(left, right) {
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _classCallCheck(instance, Constructor) {
if (!_instanceof(instance, Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
// According to their attribute descriptors Assign methods and static properties to the constructor prototype And constructor functions
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
// Assign methods and static properties to the constructor prototype And constructor functions
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
// ES6
var Parent = function () {
function Parent(name) {
_classCallCheck(this, Parent);
this.name = name;
}
_createClass(Parent, [{
key: "sayName",
value: function sayName() {
console.log('my name is ' + this.name);
return this.name;
}
}], [{
key: "sayHello",
value: function sayHello() {
console.log('hello');
}
}]);
return Parent;
}();
var Child = function (_Parent) {
_inherits(Child, _Parent);
function Child(name, age) {
var _this;
_classCallCheck(this, Child);
// Child.__proto__ => Parent
// So it's equivalent to Parent.call(this, name); yes super(name) A transformation of
// _possibleConstructorReturn Judge Parent.call(this, name) Function return value Is it null Or functions or objects .
_this = _possibleConstructorReturn(this, _getPrototypeOf(Child).call(this, name));
_this.age = age;
return _this;
}
_createClass(Child, [{
key: "sayAge",
value: function sayAge() {
console.log('my age is ' + this.age);
return this.age;
}
}]);
return Child;
}(Parent);
var parent = new Parent('Parent');
var child = new Child('Child', 18);
console.log('parent: ', parent); // parent: Parent {name: "Parent"}
Parent.sayHello(); // hello
parent.sayName(); // my name is Parent
console.log('child: ', child); // child: Child {name: "Child", age: 18}
Child.sayHello(); // hello
child.sayName(); // my name is Child
child.sayAge(); // my age is 18
pdfRecommended reading JS Inherit relevant book chapters
githubdemoES6JavaScriptJavaScriptES6 Medium classsummary
- Of the subclass constructor
__proto__Point to the parent class constructor , Inherit the static methods of the parent class .
- Of the subclass constructor
prototypeOf__proto__Point to the parent class constructorprototype, Methods that inherit the parent class .
- Call the parent constructor in the subclass constructor , Inherit the properties of the parent class . Here we go , The article is basically finished . Resources such as article code and pictures are put heregithub inhertand
demoExhibitiones6-extends, combinationconsole、sourcePanel view is better .
边栏推荐
- Overview and deployment of GFS distributed file system
- Function and usage of malloc function in C language
- Taro---day1---搭建项目
- 为什么要选择不锈钢旋转接头
- 投资场内ETF基金是靠谱吗,场内ETF基金安全吗
- [black apple series] m910x perfect black apple system installation tutorial – 2 making system USB disk -usb creation
- What are the requirements for customizing the slip ring for UAV
- 有监督、无监督与半监督学习
- [untitled]
- Every time I started the service of the project, the computer helped me open the browser, revealing the 100 lines of source code!
猜你喜欢

为什么要选择不锈钢旋转接头

Proe/creo product structure design - continuous research

【说明】Jmeter乱码的解决方法

Class文件结构和字节码指令集

DeepMind | 通过去噪来进行分子性质预测的预训练

Understand the basic structure of wechat applet project

How to build dual channel memory for Lenovo Savior r720

Introduction to memory model of JVM

LabVIEW continuous sampling and limited sampling mode

Sword finger offer 61 Shunzi in playing cards
随机推荐
面试官问:JS的继承
From small to large, why do you always frown when talking about learning
Some habits of making money in foreign lead
Which securities speculation account opening commission is the cheapest and safest
What is the e-commerce conversion rate so abstract?
云厂商为什么都在冲这个KPI?
Esxi based black Qunhui DSM 7.0.1 installation of VMware Tools
electron窗口背景透明无边框(可用于启动页面)
Is it safe to open an account online now? Novice is just on the road, ask for the answer
Modern programming languages: zig
. Mp4 video test address
Is it safe to open a new bond registration account? Is there any risk?
awk注意的几个问题
Solon 1.8.3 发布,云原生微服务开发框架
Internship: business process introduction
Is the stock investment exchange group safe? Is it reliable to open an account for free?
795 div.2 D. Max GEQ sum monotone stack
现在网上开股票账户安全吗?选择上市券商,最快8分钟开户成功
投资场内ETF基金是靠谱吗,场内ETF基金安全吗
去哪儿网(Qunar) DevOps 实践分享