


Detailed explanation of JavaScript inheritance (2)_js object-oriented
this
This represents the current object. If this is used in the global scope, it refers to the current page object window; if this is used in a function, what this refers to is based on the object on which this function is called at runtime. We can also use the two global methods apply and call to change the specific pointer of this in the function.
Let’s first look at an example of using this in the global scope:
<script type="text/javascript"> console.log(this === window); // true console.log(window.alert === this.alert); // true console.log(this.parseInt("021", 10)); // 10 </script>
This in the function is determined at runtime, not when the function is defined, as follows:
// 定义一个全局函数 function foo() { console.log(this.fruit); } // 定义一个全局变量,等价于window.fruit = "apple"; var fruit = "apple"; // 此时函数foo中this指向window对象 // 这种调用方式和window.foo();是完全等价的 foo(); // "apple" // 自定义一个对象,并将此对象的属性foo指向全局函数foo var pack = { fruit: "orange", foo: foo }; // 此时函数foo中this指向window.pack对象 pack.foo(); // "orange"
The global functions apply and call can be used to change the pointer of this in the function, as follows:
// 定义一个全局函数 function foo() { console.log(this.fruit); } // 定义一个全局变量 var fruit = "apple"; // 自定义一个对象 var pack = { fruit: "orange" }; // 等价于window.foo(); foo.apply(window); // "apple" // 此时foo中的this === pack foo.apply(pack); // "orange"
Because functions are also objects in JavaScript, we can see the following interesting examples:
// 定义一个全局函数 function foo() { if (this === window) { console.log("this is window."); } } // 函数foo也是对象,所以可以定义foo的属性boo为一个函数 foo.boo = function() { if (this === foo) { console.log("this is foo."); } else if (this === window) { console.log("this is window."); } }; // 等价于window.foo(); foo(); // this is window. // 可以看到函数中this的指向调用函数的对象 foo.boo(); // this is foo. // 使用apply改变函数中this的指向 foo.boo.apply(window); // this is window.
prototype
We have already used prototypes to simulate the implementation of classes and inheritance in Chapter 1. Prototype is essentially a JavaScript object. And every function has a default prototype attribute.
If this function is used in the scenario of creating a custom object, we call this function a constructor. For example, the following is a simple scenario:
// 构造函数 function Person(name) { this.name = name; } // 定义Person的原型,原型中的属性可以被自定义对象引用 Person.prototype = { getName: function() { return this.name; } } var zhang = new Person("ZhangSan"); console.log(zhang.getName()); // "ZhangSan"
// 定义数组的构造函数,作为JavaScript的一种预定义类型 function Array() { // ... } // 初始化数组的实例 var arr1 = new Array(1, 56, 34, 12); // 但是,我们更倾向于如下的语法定义: var arr2 = [1, 56, 34, 12];
In fact, all intrinsic data types of JavaScript have read-only prototype attributes (this is understandable: if the prototype attributes of these types are modified, the predefined methods disappear), but we can Add your own extension methods to it.
// 向JavaScript固有类型Array扩展一个获取最小值的方法 Array.prototype.min = function() { var min = this[0]; for (var i = 1; i < this.length; i++) { if (this[i] < min) { min = this[i]; } } return min; }; // 在任意Array的实例上调用min方法 console.log([1, 56, 34, 12].min()); // 1
Note: There is a trap here. After adding an extension method to the prototype of Array, this extension method will also be looped out when using for-in to loop the array.
The following code illustrates this (assuming that the min method has been extended to the Array prototype):
var arr = [1, 56, 34, 12]; var total = 0; for (var i in arr) { total += parseInt(arr[i], 10); } console.log(total); // NaN
var arr = [1, 56, 34, 12]; var total = 0; for (var i in arr) { if (arr.hasOwnProperty(i)) { total += parseInt(arr[i], 10); } } console.log(total); // 103
constructor
constructor always points to the constructor that created the current object. For example:
// 等价于 var foo = new Array(1, 56, 34, 12); var arr = [1, 56, 34, 12]; console.log(arr.constructor === Array); // true // 等价于 var foo = new Function(); var Foo = function() { }; console.log(Foo.constructor === Function); // true // 由构造函数实例化一个obj对象 var obj = new Foo(); console.log(obj.constructor === Foo); // true // 将上面两段代码合起来,就得到下面的结论 console.log(obj.constructor.constructor === Function); // true
But when the constructor encounters the prototype, something interesting happens.
We know that each function has a default attribute prototype, and the constructor of this prototype points to this function by default. As shown in the following example:
function Person(name) { this.name = name; }; Person.prototype.getName = function() { return this.name; }; var p = new Person("ZhangSan"); console.log(p.constructor === Person); // true console.log(Person.prototype.constructor === Person); // true // 将上两行代码合并就得到如下结果 console.log(p.constructor.prototype.constructor === Person); // true
function Person(name) { this.name = name; }; Person.prototype = { getName: function() { return this.name; } }; var p = new Person("ZhangSan"); console.log(p.constructor === Person); // false console.log(Person.prototype.constructor === Person); // false console.log(p.constructor.prototype.constructor === Person); // false
It turns out that when overwriting Person.prototype, it is equivalent to the following code operation:
Person.prototype = new Object({ getName: function() { return this.name; } });
function Person(name) { this.name = name; }; Person.prototype = { getName: function() { return this.name; } }; var p = new Person("ZhangSan"); console.log(p.constructor === Object); // true console.log(Person.prototype.constructor === Object); // true console.log(p.constructor.prototype.constructor === Object); // true
function Person(name) { this.name = name; }; Person.prototype = new Object({ getName: function() { return this.name; } }); Person.prototype.constructor = Person; var p = new Person("ZhangSan"); console.log(p.constructor === Person); // true console.log(Person.prototype.constructor === Person); // true console.log(p.constructor.prototype.constructor === Person); // true
In the next chapter we will improve the implementation of the Person-Employee class and inheritance mentioned in the first chapter.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

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

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

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

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more
