Home Web Front-end JS Tutorial Learn javascript object-oriented and understand javascript prototype and prototype chain_javascript skills

Learn javascript object-oriented and understand javascript prototype and prototype chain_javascript skills

May 16, 2016 pm 03:22 PM
javascript prototype prototype chain

Look at a picture first and sort it out.

1. Basic concepts
[Prototype Chain]Each constructor has an object, the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. Then, if the prototype object is equal to an instance of another prototype, the prototype object at this time will contain a pointer to the other prototype. Correspondingly, the other prototype also contains a pointer to another constructor. If another prototype is an instance of another prototype, then the above relationship still holds. This layer-by-layer progression forms a chain of instances and prototypes.
【Prototype Object】This object contains properties and methods that can be shared by all instances of a specific type. All reference types inherit Object by default, and this inheritance is also implemented through the prototype chain. The default prototype of all functions is an instance of Object, so the default prototype will contain an internal pointer pointing to Object.prototype. This is why all custom types will inherit the toString() and valueOf() methods
[Constructor]The difference between constructors and other functions lies in the way they are called. Generally speaking, as long as a function is called through the new operator, it can be used as a constructor; if it is not called through the new operator, it is no different from an ordinary function.
[Note] User-defined functions and built-in constructors in JavaScript can be used as constructors
[How to write constructors]Constructors should always start with an uppercase letter, while non-constructors should start with a lowercase letter. This approach is borrowed from other OO languages, mainly to distinguish it from other functions in ECMAScript; because the constructor itself is also a function, but it can be used to create objects
[Three usage scenarios of constructor]
[a] Use as constructor

var person = new Person("Nicholas",29,"software Engineer");
person.sayName();
Copy after login

[b] Called as a normal function

Person("greg",27,"doctor");//添加到window
window.sayName();//"Greg"
Copy after login

[c] Call
in the scope of another object

var o = new Object();
Person.call(o,"Kristen",25,"Nurse");
o.sayName();//"Kristen"
Copy after login

【prototype属性】只要创建了一个新函数,就会根据一组特定的规则为该函数创建一个prototype属性,这个属性指向函数的原型对象。
[注意]只有函数才有prototype属性,object没有prototype属性
【constructor属性】在默认情况下,所有原型对象都会自动获得一个constructor(构造函数)属性,这个属性包含一个指向prototype属性所在函数的指针
[注意]创建了自定义的构造函数之后,其原型对象默认只会取得constructor属性,至于其他方法则都是从Object继承而来的
【_proto_和[[prototype]]】当调用构造函数创建一个新实例后,该实例的内部将包含一个指针(内部属性),指向构造函数的原型对象。ECMA-262第5版管这个指针叫[[prototype]]。虽然在脚本中标准的方式访问[[prototype]],但firefox\safari\chrome在每个对象上都支持一个属性_proto_;而在其他实现中,这个属性对脚本则是完全不可见的。这个连接存在于实例与构造函数的原型对象之间,而不是存在于实例与构造函数之间
二、基本操作  
【原型链查询】每当代码读取某个对象的某个属性时,都会执行一次搜索,目标是具有给定名字的属性。搜索首先从对象实例本身开始,如果在实例中找到了具有给定名字的属性,则返回该属性的值;如果没有找到,则继续搜索指针指向的原型对象,在原型对象中查找具有给定名字的属性,如果找到了这个属性,则返回该属性的值。
【添加实例属性】当为对象实例添加一个属性时,这个属性就会屏蔽原型对象中保存的同名属性;换句话说,添加这个属性只会阻止我们访问原型中的那个属性,但不会修改那个属性,即使将这个属性设置为null,也只会在实例中设置这个属性,而不会恢复其指向原型的连接。不过,使用delete操作符则可以完全删除实例属性,从而让我们能够重新访问原型中的属性。
【原型的动态性】由于在原型中查找值的过程是一次搜索,因此我们对原型对象所做的任何修改都能立即从实例上反映出来,即使是先创建了实例后修改原型也照样如此。
[注意]不推荐在产品化的程序中修改原生对象的原型

function Person(){};
var friend = new Person();
Person.prototype.sayHi = function(){
  alert('hi');
}
friend.sayHi();//"hi"  
Copy after login

【重写原型】调用构造函数时会为实例添加一个指向最初原型的[[prototype]]指针,而把原型修改为另外一个对象就等于切断了构造函数与最初原型之间的联系。实例中的指针仅指向原型,而不指向构造函数。
三、基本方法  
[1]isPrototypeOf():判断实例对象和原型对象是否存在于同一原型链中,只要是原型链中出现过的原型,都可以说是该原型链所派生的实例的原型

function Person(){};
var person1 = new Person();
var person2 = new Object();
console.log(Person.prototype.isPrototypeOf(person1));//true
console.log(Object.prototype.isPrototypeOf(person1));//true
console.log(Person.prototype.isPrototypeOf(person2));//false
console.log(Object.prototype.isPrototypeOf(person2));//true
Copy after login

[2]ECMAScript5新增方法Object.getPrototypeOf():这个方法返回[[Prototype]]的值

function Person(){};
var person1 = new Person();
var person2 = new Object();
console.log(Object.getPrototypeOf(person1)); //Person{}
console.log(Object.getPrototypeOf(person1) === Person.prototype); //true
console.log(Object.getPrototypeOf(person1) === Object.prototype); //false
console.log(Object.getPrototypeOf(person2)); //Object{}  
Copy after login

[3]hasOwnProperty():检测一个属性是否存在于实例中

function Person(){
  Person.prototype.name = 'Nicholas';
}
var person1 = new Person();
//不存在实例中,但存在原型中
console.log(person1.hasOwnProperty("name"));//false
//不存在实例中,也不存在原型中
console.log(person1.hasOwnProperty("no"));//false
person1.name = 'Greg';
console.log(person1.name);//'Greg'
console.log(person1.hasOwnProperty('name'));//true
delete person1.name;
console.log(person1.name);//"Nicholas"
console.log(person1.hasOwnProperty('name'));//false  
Copy after login

[4]ECMAScript5的Object.getOwnPropertyDescriptor():只能用于取得实例属性的描述符,要取得原型属性的描述符,必须直接在原型对象上调用Object.getOwnPropertyDescription()方法

function Person(){
  Person.prototype.name = 'Nicholas';
}
var person1 = new Person();
person1.name = 'cook';
console.log(Object.getOwnPropertyDescriptor(person1,"name"));//Object {value: "cook", writable: true, enumerable: true, configurable: true}
console.log(Object.getOwnPropertyDescriptor(Person.prototype,"name"));//Object {value: "Nicholas", writable: true, enumerable: true, configurable: true}
Copy after login

[5]in操作符:在通过对象能够访问给定属性时返回true,无论该属性存在于实例还是原型中

function Person(){}
var person1 = new Person();
person1.name = 'cook';
console.log("name" in person1);//true
console.log("name" in Person.prototype);//false
var person2 = new Person();
Person.prototype.name = 'cook';
console.log("name" in person2);//true
console.log("name" in Person.prototype);//true
Copy after login

[6]同时使用hasOwnProperty()方法和in操作符,来确定属性是否存在于实例中

//hasOwnProperty()返回false,且in操作符返回true,则函数返回true,判定是原型中的属性
function hasPrototypeProperty(object,name){
  return !object.hasOwnProperty(name) && (name in object);
}
function Person(){
  Person.prototype.name = 'Nicholas';
}
var person1 = new Person();
console.log(hasPrototypeProperty(person1,'name'));//true
person1.name = 'cook';
console.log(hasPrototypeProperty(person1,'name'));//false
delete person1.name;
console.log(hasPrototypeProperty(person1,'name'));//true
delete Person.prototype.name;
console.log(hasPrototypeProperty(person1,'name'));//false
Copy after login

[7]ECMAScript5的Object.keys()方法:接收一个对象作为参数,返回一个包含所有可枚举属性的字符串数组
[注意]一定要先new出实例对象再使用该方法,否则为空

function Person(){
  Person.prototype.name = 'Nicholas';
  Person.prototype.age = 29;
  Person.prototype.job = 'Software Engineer';
  Person.prototype.sayName = function(){
    alert(this.name);
  }  
};
var keys = Object.keys(Person.prototype);
console.log(keys);//[]
var p1 = new Person();
p1.name = "Rob";
p1.age = 31;
var keys = Object.keys(Person.prototype);
console.log(keys);//["name","age","job","sayName"]
var p1Keys = Object.keys(p1);
console.log(p1Keys);//["name","age"]
Copy after login

[8]ECMAScript5的Object.getOwnPropertyNames()方法:接收一个对象作为参数,返回一个包含所有属性的字符串数组
[注意]一定要先new出实例对象再使用该方法,否则只有constructor

function Person(){
  Person.prototype.name = 'Nicholas';
  Person.prototype.age = 29;
  Person.prototype.job = 'Software Engineer';
  Person.prototype.sayName = function(){
    alert(this.name);
  }  
};
var keys = Object.getOwnPropertyNames(Person.prototype);
console.log(keys);//["constructor"]
var p1 = new Person();
var keys = Object.getOwnPropertyNames(Person.prototype);
console.log(keys);//["constructor", "name", "age", "job", "sayName"]
Copy after login

希望本文所述对大家学习javascript程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles