js object prototype and constructor

1. The prototype of an object is an object, and the prototype of a function is also an object

Every object has a prototype, and the prototype is also an object. There are many functions in the prototype object. We can get the prototype and add properties through the method of obj.__proto__, and the objects created in this prototype will inherit this property.

var person1 = {
    name: "obj1",
    age: 18,
}
var person2 ={// 字母量创建一个对象
    gender: "girl"
} 
person1.__proto__.perosnif = "是人类" // 给原型添加属性
console.log(person2.perosnif); // 是人类
console.log(person2.name); // undefined
console.log(person2.gender); // girl

When searching for attributes, it will first look for its own attributes. If it cannot find its own attributes, it will go to the prototype (according to the prototype chain) to search, and if it cannot find it, it will output undefined.

It is worth noting that the prototype of the function is an object rather than a function, use fun.prototype to get the prototype:

function foo () {

}

console.log(foo.prototype); // {constructor: ƒ}

2. Object prototype memory performance 

If a sing function is defined on the prototype, our objects can be used directly and are exactly the same.

Because they are both the sing function of the prototype object on the same memory used

person1.__proto__.sing = function() {
    console.log("singing");
}

console.log(person1.sing === person2.sing); // true

3. Create an object using a constructor

To construct an object using a function, use the new function method:

// Person 构造函数
function Person(name,age) { // 传入两个参数
	this.name = name;
	this.age = age;
	this.sing = function() {
		console.log("singing")
	}
}

var person1 = new Person("张三",18)

Note here that when we create the second object, the sing method inside is different, because every time Person is executed, a new function will be recreated to assign

var person1 = new Person("张三",18)
var person2 = new Person("李四",19)

console.log(person1.sing === person2.sing); // false

The memory performance is as follows:

 Defining the method on the prototype resolves:

function Person(name,age) {
	this.name = name;
	this.age = age;
}

Person.prototype.sing = function() {
    console.log(this.name + " is singing");
}

var person1 = new Person("张三",18)
var person2 = new Person("李四",19)

console.log(person1.sing === person2.sing); // true
person1.sing() // 张三 is singing

Memory performance: at this time, methods in the same prototype object are shared 

Guess you like

Origin blog.csdn.net/m0_66492535/article/details/127966813