How does javascript create an object?

function Person(name) {
    this.name = name;
    this.say = function() {
        console.info('I am ' + this.name);
    }
}
var p=new Person('stackoverflow');

Someone will tell me that the codes above are equal:

function Person(name) {
    this.name = name;
    this.say = function() {
        console.info('I am ' + this.name);
    }
}

var p={};
Person.call(p,'stackoverflow');

It's true?

If so, what about the prototype?

Each object in javascripte owns a prototype, and the prototype chain keeps exempt from obejcts, I wonder if this prototype does something or not.

In this example, when the 'p' object is created, does it invoke some inline method of the Person superclass?

By the way, I want to know what the syntax does var p=new Person('stackoverflow');?


----------------- update ------------------

function Person(name) {
    this.name = name;
}
Person.prototype.say = function() {
    console.info('I am ' + this.name);
}

How about if I put protection in human function:

function Person(name) {
    this.name = name;
    Person.prototype.say = function() {
        console.info('I am ' + this.name);
    }
}
+3
source share
2 answers

The code:

var p=new Person('stackoverflow');

Person. , javascript , , :

Person.call(p,'stackoverflow');

Person p- ( , this p-). , , , , - , .

, - Person:

Person.prototype={test:"test"}

Person, , . , "", , - . , - "".

+2

,

var p=new Person('stackoverflow');

:

var p={};
p.__proto__ = Person.prototype;
Person.call(p,'stackoverflow');

, __proto__ JavaScript ( ).

0

Source: https://habr.com/ru/post/1771457/


All Articles