Functions, objects, and class relationship records in JavaScript

Source: Internet
Author: User
Tags function prototype hasownproperty

Relationship of functions and objects

Functions can have properties, objects can have attributes, and an operator can be used to new return an instantiated object of a function before the function name

function fn () {}fn.a = ‘haha‘console.log(fn.a) //"haha"let obj = {}obj.a = ‘heihei‘console.log(obj.a) //"heihei"let newObj = new fn()

Each function has an attribute (prototype) prototype object, which discovers constructor attributes and __poroto__ attributes, and constructor points to the constructor function that created it, and here it is clear that the function has a constructor, and this __poroto__ is the same thing as the prototype of its constructor. , as shown in the dotted-line CFP is the prototype of the constructor, and the small CF is an object instance created by CF

// fn.prototype{    constructor: ? doSomething(),    __proto__: {        constructor: ? Object(),        hasOwnProperty: ? hasOwnProperty(),        isPrototypeOf: ? isPrototypeOf(),        propertyIsEnumerable: ? propertyIsEnumerable(),        toLocaleString: ? toLocaleString(),        toString: ? toString(),        valueOf: ? valueOf()    }}

We can either add attributes to the CF or prototype add

Distinguishing: Adding attributes on a function, adding a constructor on a build instance, adding a function prototype

function fn() {    this.c = ‘c‘}fn.a = ‘a‘fn.prototype.b = ‘b‘let obj = new fn()obj.d = ‘d‘// fn.prototype 上定义 属性b ,obj定义了属性d,fn上添加了属性 a,// fn函数内部有个this的属性c, 那么obj有几个属性呢? 答案是 c b d

The following is to analyze why this, first of all the CF P1, P2 in the object instance is present, refer to the following code

function CF(){    this.p1 = ‘p1‘,    this.p2 = ‘p2‘}let cf1 = new CF()

See

You can see that the attributes appear on the object instance, and now it's time to say what happened to the build instance.

    1. Create a new object cf1
    2. The scope of the constructor is assigned to the new object, this points to the new object
    3. Executes the code in the constructor, that is, the injected property
    4. return new Object

However, the property constructor on this does not have a property that is directly defined on the function, which is of course the case, by prototyoe setting the CFP position in the diagram, the instance inherits it, that is, the object instance gets these attributes, and the object instance is prototype created in effect before the attribute is added.
The relationship between the function and the object is clear, the constructor can be used to create the object, and you can get the function prototype properties and methods, you can also in the constructor through this for it to set some not public property methods, etc.

Extended:

    1. The properties added with this have a certain "private" nature, but there are some areas to be aware of, see the code below

      function fn() {  let value = ‘a‘  this.a = ‘a‘  this.privateValues = function (){    return value  }  }let newObj1 = new fn()let newObj2 = new fn()console.log(newObj1.a === newObj2.a) //true,基本类型的比较只比较值console.log(newObj1.privateValues === newObj2.privateValues) // false,每次进入对象都不相同

      Use functions to wrap them back with better "private" sex.

    2. Overriding a prototype object with an object

      function fn() {}fn.prototype = {  name: ‘kangkang‘,  sayName: {    console.log(this.name)  }}

      Using object overrides will cause a new prototype object to be created, and the object will constructor no longer point to the constructor, which requires a re-designation of the next

      function fn() {}fn.prototype = {  constructor: fn  name: ‘kangkang‘,  sayName: {    console.log(this.name)  }}
Inherited

Here the succession wants to have a more profound understanding, first need to introduce the following prototype chain:
Each instance object (object) has a private property (called Proto) that points to its prototype object (prototype). The prototype object also has a prototype object of its own, layer up until the prototype object of an object is null. By definition, NULL does not have a prototype, and as the last link in this prototype chain

Reference MDN
Since each instance inherits the properties or methods on the prototype object on the prototype chain, when you use a property that is not on an instance, and you look for it in the first layer of the prototype chain, then the concept of inheritance is very clear, and we give the prototype object to the object that needs to inherit? Actually, there's a problem.

function father() {}function son() {}father.prototype.sayHello = function() {  console.log(‘hello‘)}son.prototype = father.prototype let obj = new son()obj.sayHello() // hello// father.prototype.sayHello = function() {  console.log(‘haha‘)} obj.sayHello() // haha  

The above "inheritance" is problematic, not only interacting with each other, but when father modifies the prototype, it directly affects son, making improvements

function father() {}function son() {}  father.prototype.sayHello = function() {    console.log(‘hello‘)} function wa() {  }  wa.prototype = father.prototype  son.prototype = new wa()son.prototype.constructor = sonson.prototype.sayHello = function() {console.log(‘sss‘)}    father.prototype.sayHello() //hello

A new method has been introduced in ECMAScript 5: object.create (). You can call this method to create a new object. The prototype of a new object is the first parameter passed in when the Create method is called

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

There is still a disadvantage, when the prototype object has a reference type is worth the attribute

function a () {  this.obj = {    name: ‘kangkang‘,    age: 3  }}function b() {  this.b = ‘b‘}    b.prototype = new a()var c = new b()var d = new b()c.obj.name=‘xixi‘console.log(d.obj.name) //xixi

At this point, the created instance gets the same value each time it gets the reference value property of the constructor, and the value holds the address of the reference type, which is naturally the same reference value, so the interaction between them, the workaround
Look at the code below

function fn (name) {    this.score = [90,98,99]    this.name = name}function a () {  fn.call(this,‘kangkang‘)  this.age = 3}var c = new a()var d = new a()c.score[0] = 100console.log(c.score) //[100, 98, 99]console.log(d.score) //[90, 98, 99]

This method lacks the inheritance on the prototype, so the combination is

function fn (name) {    this.score = [90,98,99]    this.name = name}fn.prototype.sayName = function() { console.log(this.name) }function a () {  fn.call(this,‘kangkang‘)  this.age = 3}a.prototype = new fn()a.prototype.constructor = avar c = new a()var d = new a()c.score[0] = 100console.log(c.score) //[100, 98, 99]console.log(d.score) //[90, 98, 99]console.log(c.sayName()) // kangkang
Class

ES6 implementation class , which has class constructor static extends super These keywords complete implementation of the "class" function, it is the syntax of sugar, is based on the concept of the above-mentioned prototype implementation

    1. Define the class name first letter uppercase
    2. The constructor method is a special method for creating and initializing an object created using class, with only one
    3. Use the Super keyword to invoke the constructor of a parent class
    4. The extends keyword is used in a class declaration or class expression to create a class as a subclass of another class.
    5. The static keyword is used to define a statically defined method of a class. Calling a static method does not require instantiating the class, but it cannot call a static method through a class instance. Static methods are typically used to create tool functions for an application.
class Polygon {    constructor(height, width) {    this.height = height;    this.width = width;  }}class Square extends Polygon {  constructor(sideLength) {    super(sideLength, sideLength);  }  get area() {    return this.height * this.width;  }  set sideLength(newLength) {    this.height = newLength;    this.width = newLength;  }}var square = new Square(2);

staticUsage

class Point {    constructor(x, y) {        this.x = x;        this.y = y;    }    static distance(a, b) {        const dx = a.x - b.x;        const dy = a.y - b.y;        return Math.hypot(dx, dy);    }}const p1 = new Point(5, 5);const p2 = new Point(10, 10);console.log(Point.distance(p1, p2)); //7.0710678118654755// 注意此处不是从实例中调用它的

Expand:
ES6 attribute shorthand and method shorthand reference Nanyi Teacher's blog

const o = {  method() {    return "Hello!";  }};// 等同于const o = {  method: function() {    return "Hello!";  }};function f(x, y) {  return {x, y};}// 等同于function f(x, y) {  return {x: x, y: y};}f(1, 2) // Object {x: 1, y: 2}

The above for the access to the summary of the information, if you want to be detailed and accurate also please consult the party can discriminate the income

Functions, objects, and class relationship records in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.