Home  >  Article  >  Web Front-end  >  JavaScript learning summary of prototype objects (organized and shared)

JavaScript learning summary of prototype objects (organized and shared)

WBOY
WBOYforward
2022-01-17 18:20:431215browse

This article brings you relevant knowledge about prototype objects in JavaScript. I hope it will be helpful to you.

JavaScript learning summary of prototype objects (organized and shared)

Classes you understand? What are the characteristics of classes? (Encapsulation, inheritance, polymorphism)

A class is actually a "special function". Just like the function expressions and function declarations you can define, the class syntax also consists of two Components: Class declaration and class expression. The body of the class is executed in strict mode.

The class body of a class is the part enclosed by a pair of curly braces {}, which is where the class members are defined. [Members are mainly methods or constructors]

All methods of a class are equivalent to being defined on the prototype attribute of the class. Calling a method on an instance of a class is equivalent to calling a method on the prototype.

class A(){
    constructor(){}
    a(){}
    b(){}
}
//等价于
A.prototype={constructor(){},a(){},b(){}}

Composition:

  • Constructor:

The constructor method is a special method used to create and initialize an object created by class. A class can only have one constructor. If there are multiple constructors, an error will be reported. If there is no constructor, an empty constructor will be added by default. The constructor returns the real column object [ie this] by default. A constructor can use the super keyword to call a parent class constructor.

  • Attributes

  • Prototype method: This method does not need to add the function keyword, just put the definition of the function directly. Commas cannot be used to separate methods, otherwise an error will be reported.

  • Static method: Use static to define a static method and call a static method. It cannot be called by the instance column of the class, but can only be called by using the class.

  • Value function getter and storage function setter: Use the get and set keywords in the class to set the storage and value functions for a certain attribute and intercept the access to the attribute. Behavior.

Class syntax:

  • Class declaration: Use the class keyword

class Rectangle{
    constructor(height,width){
        this.height=height;
        this.width=width;
    }
}

Note: The difference between function declaration and class declaration: class declaration will not be promoted, function declaration will be promoted.

Class expression: Class expression can be named or anonymous. The name given to a named class expression is the local name of the class's body.

 let Rectangle=class{//匿名类
      constructor(height,width){
            this.height=height;
            this.width=width;
        }
 }
 let Rectangle= class Rectangle{//命名类
      constructor(height,width){
            this.height=height;
            this.width=width;
        }
 }

Use extends to create subclasses:

The extends keyword is used in a class declaration or class expression to create a class as a subclass of another class.

Use super to call the super class:

The super keyword is used to call functions on the parent object of the object

Characteristics of the class:

- Encapsulation: Mainly through functions, the setting of private properties and methods is mainly achieved through block-level scope

- Polymorphism: Can be called through functions, because parameters can Changeable

- Inheritance: mainly through the prototype chain

What happens when we new an ordinary function?

  • Create a new object using the prototype attribute of the constructor (note the difference from the private field [[prototype]]) as the prototype;

  • Pass this and the calling parameters to the constructor and execute;

  • If the constructor returns an object, return it, otherwise return the object created in the first step.

new Such behavior attempts to make the syntax of function objects similar to classes. However, it objectively provides two ways. One is to add Attributes, the second is to add attributes to the prototype attribute of the constructor.

Does the function name after new have to be capitalized?

No, mainly for the convenience of classification. General constraints are uppercase

How to understand ProtoType? The process of finding a certain attribute of an object?

prototype:

Each function has a special attribute called the prototype object [prototype]

js is based on In a prototype language, each object has a prototype object, and the object uses its prototype as a template and inherits methods and properties from the prototype. These properties and methods are defined on the prototype attribute above the object's constructor, not on the object instance itself.

Prototype objects can have prototype objects and inherit methods and properties from them, layer by layer, layer by layer until the prototype object of an object is null. This is the prototype chain.

When creating an object instance, a link is established between the object instance and its constructor [__proto__ attribute, which is derived from the prototype attribute of the constructor. That is, __proto__ and the prototype of the constructor point to the same object] Object.getPrototypeof(new Foobar()) and Foobar.prototype are equal.

Object.create(). Creates a new object from the specified prototype object. var newObj=Object.create(obj). Then newObj's __proto__=obj

Each real column object inherits a constructor attribute from the prototype. This property points to the constructor that constructs this instance.

Generally, attributes are defined in the constructor and methods are defined in the prototype.

一般由构造函数实列化出一个新对象,新对象的原型对象是一个constructor和一个Object的原型对象组成。而函数构造函数的原型对象是也是由另外一个constructor和一个Function的原型对象组成。

    var F=function(){};
    Object.prototype.a=function(){};
    Function.prototype.b=function(){};
    var f=new F();
    //上面的结果是,f能取到a,不能取到b.
    详解:
        1.f.__proto__===F.prototype
        2.F.prototype.__proto__===Object.prototype(所以f可以访问a)
        3.f.constructor===F
        4.F.__proto__===Function.prototype(所以f.constructor.b可以访问)

查找属性的过程:

1.先查找自己身属性是否由包含该属性。

2.如果没有,才会沿着原型链,层层向上搜索,直到找到名字的属性

3.如果找到最后原型链的末尾,即最后的原型为null,那就是没有找到该属性。就会返回undefined

不同方法创建对象和原型链

1.使用语法结构创建对象

var o = {a: 1};
// o 这个对象继承了 Object.prototype 上面的所有属性
// o 自身没有名为 hasOwnProperty 的属性
// hasOwnProperty 是 Object.prototype 的属性
// 因此 o 继承了 Object.prototype 的 hasOwnProperty
// Object.prototype 的原型为 null
// 原型链如下:
// o ---> Object.prototype ---> null
var a = ["yo", "whadup", "?"];
// 数组都继承于 Array.prototype 
// (Array.prototype 中包含 indexOf, forEach 等方法)
// 原型链如下:
// a ---> Array.prototype ---> Object.prototype ---> null
function f(){
return 2;
}
// 函数都继承于 Function.prototype
// (Function.prototype 中包含 call, bind等方法)
// 原型链如下:
// f ---> Function.prototype ---> Object.prototype ---> null

2.使用构造函数创建对象

function A() {
this.a = 1;
this.b = 2;
}
A.prototype = {
write: function(){
    console.log(this.a);
}
};
var a = new A();
// a 是生成的对象,他的自身属性有 'a' 和 'b'。

3.使用Object.create()创建对象(ES5)

var a = {a: 1}; 
// a ---> Object.prototype ---> null
var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (继承而来)
var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null
var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype
使用

4.使用class创建对象(ES6)

class A {
constructor(a, b) {
    this.a = a;
    this.b = b;
}
}
class B extends A {
constructor(a,b,c) {
    super(a, b);
    this.c=c;
}
get ab() {
    return this.a + this.b;
}
set d(d) {
    this.a = d;
    this.b = d;
    this.c = d;
}
}
var a= new A('a','b');//a的原型对象是 A.prototype
var b = new B('a','b','c');//    //b的原型对象是 B.prototype

当一个对象设置属性时都发生了什么?

如果对象包含普通数据访问属性,直接赋值只会修改属性值

    var a={b=1}//因为b是a的普通属性,数据类型为Number

    a.b="a";  //直接更改b的类型为String,且赋值为'a'.

如果对象找不到该属性,且原型链也找不到,就直接默认添加一个属性到该对象上。

    var a={}//b不是a的普通属性,且原型链上也没有

    a.b="a";  //直接在a上添加b的类型,为String,且赋值为'a'.

如果属性b,存在于原型链上

//在原型链上层存在名为b的普通数据访问属性并且没有标记为只读(writable:false),那就会直接在a中添加一个名为b的新属性,且值为'a'。而原型链上的b就会被屏蔽掉:

    function A(){};
    A.prototype.b=1;
    var a=new A();
    a.b='a';

//在原型链上层存在b,但是他被标记为只读,那么无法修改已有属性,或者在a中创建屏蔽属性。如果运行在严格模式下,代码会抛出一个错误,否则,这条赋值语句会被忽略,总之,不会发生屏蔽。

    function A(){
    };
A.prototype.b=1
    Object.defineProperty(A.prototype,'b',{
        configurable:true,
        writable:false
    })
    var a=new A();
    a.b='a';//结果a.b还是1

【相关推荐:javascript学习教程

The above is the detailed content of JavaScript learning summary of prototype objects (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete