深入解析 JavaScript 构造函数:特性、用法与原型链

ops/2024/10/24 19:09:08/

在 JavaScript 中,构造函数是实现面向对象编程的关键工具之一。它与 this 关键字、箭头函数的作用域链以及原型和原型链紧密相关。本文将全面深入地探讨 JavaScript 构造函数的各个方面。

一、构造函数的定义与用法

构造函数是一种特殊的函数,用于创建对象。其名称通常以大写字母开头,以区别于普通函数。例如:

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

使用 new 关键字调用构造函数可以创建对象实例。例如:

javascript">let person1 = new Person('Alice', 30);
let person2 = new Person('Bob', 25);
console.log(person1); // { name: 'Alice', age: 30 }
console.log(person2); // { name: 'Bob', age: 25 }

二、构造函数的特性

(一)创建对象实例

当使用 new 调用构造函数时,会自动创建一个新对象,在构造函数内部通过 this 引用该对象。

(二)属性初始化

构造函数可以接受参数来初始化对象的属性,根据不同输入创建具有不同属性值的对象。例如:

javascript">function Rectangle(width, height) {this.width = width;this.height = height;
}
const rect = new Rectangle(5, 10);
console.log(rect); // { width: 5, height: 10 }

(三)方法继承

可以在构造函数内部定义方法,这些方法会被创建的对象实例继承。例如:

javascript">function Animal(name) {this.name = name;this.sayName = function() {console.log(`My name is ${this.name}.`);};
}
const animal = new Animal('Cat');
animal.sayName(); // My name is Cat

(四)原型共享

每个构造函数都有一个 prototype 属性指向原型对象,原型对象上的属性和方法可被该构造函数创建的所有对象实例共享。例如:

javascript">function Person() {}
Person.prototype.sayHello = function() {console.log('Hello!');
};
const person1 = new Person();
const person2 = new Person();
person1.sayHello(); // Hello!
person2.sayHello(); // Hello!

(五)可扩展性

通过在构造函数的原型上添加属性和方法,可以扩展对象,无需修改构造函数本身。例如:

javascript">function Shape() {}
Shape.prototype.draw = function() {console.log('Drawing a shape.');
};
function Circle() {}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.drawCircle = function() {console.log('Drawing a circle.');
};
const circle = new Circle();
circle.draw(); // Drawing a shape.
circle.drawCircle(); // Drawing a circle.

(六)与 new 关键字的关系

构造函数必须与 new 一起使用,否则可能导致意外结果,如 this 指向全局对象。例如:

javascript">function Person(name) {this.name = name;
}
const person = Person('Alice');
console.log(person); // undefined
console.log(window.name); // 'Alice'const properPerson = new Person('Bob');
console.log(properPerson); // { name: 'Bob' }
console.log(properPerson.name); // 'Bob'

三、构造函数中的 this 关键字

(一)指向新创建的对象实例

在构造函数被调用时,this 指向正在创建的新对象,可用于为新对象添加属性和方法。例如:

javascript">function Person(name, age) {this.name = name;this.age = age;this.sayHello = function() {console.log(`Hello, I am ${this.name}, ${this.age} years old.`);};
}
const person1 = new Person('Alice', 30);
person1.sayHello(); // Hello, I am Alice, 30 years old.

(二)方法调用中的 this

当对象的方法被调用时,this 通常指向该对象。例如:

javascript">const obj = {message: 'Hello',printMessage: function() {console.log(this.message);}
};
obj.printMessage(); // Hello

(三)丢失上下文

某些情况下,this 的指向可能会丢失,如将对象方法赋值给变量后调用。例如:

javascript">const obj = {message: 'Hello',printMessage: function() {console.log(this.message);}
};
const func = obj.printMessage;
func(); // undefined(在严格模式下会报错)

(四)使用 callapply 和 bind 方法改变 this 指向

1. 解释

在 JavaScript 中,callapply 和 bind 方法都是用于改变函数执行时的 this 指向的。这在需要动态地确定函数内部 this 的指向时非常有用,尤其是在回调函数、面向对象编程中的方法调用等场景中。

2. call 方法

  • 语法function.call(thisArg, arg1, arg2,...)
  • 作用:立即调用一个函数,并指定函数内部的 this 指向为 thisArg,后面可以跟多个参数依次传递给被调用的函数。
  • 示例
javascript">function greet() {console.log(`Hello, I am ${this.name}.`);
}
const person = { name: 'Bob' };
greet.call(person); // Hello, I am Bob.

3. apply 方法

  • 语法function.apply(thisArg, [argsArray])
  • 作用:与 call 类似,也是立即调用一个函数并指定 this 指向为 thisArg,但参数是以数组的形式传递。
  • 示例
javascript">function sum(a, b) {return this.value + a + b;
}
const obj = { value: 10 };
const result = sum.apply(obj, [5, 3]);
console.log(result); // 18

4. bind 方法

  • 语法const newFunction = function.bind(thisArg, arg1, arg2,...)
  • 作用:创建一个新函数,这个新函数的 this 被永久地绑定到指定的 thisArg 上,并且可以预先传递一些参数。新函数可以在以后被调用,并且其 this 指向不会再改变。
  • 示例
javascript">function greet() {console.log(`Hello, I am ${this.name}.`);
}
const person = { name: 'Charlie' };
const boundGreet = greet.bind(person);
boundGreet(); // Hello, I am Charlie.

5. 区别总结

  • call 和 apply 都是立即执行函数,而 bind 是返回一个新函数,不会立即执行。
  • call 和 apply 的主要区别在于传递参数的方式,call 是依次列出参数,apply 是通过数组传递参数。

四、箭头函数的作用域链

(一)与普通函数作用域链的相似之处

  • 遵循词法作用域规则,函数定义时确定可访问的变量范围。例如:
javascript">const outerVariable = 'outer';
function outerFunction() {const innerVariable = 'inner';const arrowFunc = () => {console.log(outerVariable);console.log(innerVariable);};arrowFunc();
}
outerFunction(); // outer inner

  • 箭头函数可嵌套在普通函数或其他箭头函数中,作用域链反映嵌套关系。例如:
javascript">function outer() {const outerVar = 'outer';function middle() {const middleVar = 'middle';const innerArrow = () => {console.log(outerVar);console.log(middleVar);};innerArrow();}middle();
}
outer(); // outer middle

(二)箭头函数作用域链的特殊之处

  • 不绑定自己的 thisargumentssuper 或 new.target,而是继承外层函数的值。例如:
javascript">const obj = {value: 10,method: function() {const arrowFunc = () => {console.log(this.value);};arrowFunc();}
};
obj.method(); // 10

  • 简洁的语法使作用域链更清晰,在回调函数等场景中可避免 this 指向问题。例如:
javascript">const numbers = [1, 2, 3];
numbers.forEach((num) => {console.log(num);
}); // 1 2 3

(三)作用域链与执行顺序的关系

作用域链决定了代码的执行顺序,JavaScript 引擎根据作用域链查找变量和函数。例如:

javascript">function outerFunction() {const outerVariable = 'outer';function innerFunction() {console.log(outerVariable);}return innerFunction;
}
const newFunction = outerFunction();
newFunction(); // outer
console.log(outerVariable); // 报错:ReferenceError: outerVariable is not defined(在全局作用域中无法访问 outerVariable)

五、构造函数的使用场景

(一)创建对象实例

用于模拟面向对象编程,创建具有相似结构和行为的多个对象。例如:

javascript">function Character(name, health, attackPower) {this.name = name;this.health = health;this.attackPower = attackPower;this.attack = function(target) {target.health -= this.attackPower;console.log(`${this.name} attacks ${target.name}. ${target.name}'s health is now ${target.health}.`);};
}
const player = new Character('Player 1', 100, 10);
const enemy = new Character('Enemy 1', 80, 8);
player.attack(enemy); // Player 1 attacks Enemy 1. Enemy 1's health is now 72.

(二)封装数据和行为

可通过构造函数和闭包模拟一定程度的封装,保护内部数据。例如:

javascript">function Counter() {let count = 0;this.increment = function() {count++;console.log(count);};this.decrement = function() {count--;console.log(count);};
}
const counter = new Counter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1

(三)模块模式

结合闭包实现模块模式,创建单例对象或封装特定功能的模块。例如:

javascript">function Logger() {const logs = [];function addLog(message) {logs.push(message);console.log(`Logged: ${message}`);}function getLogs() {return logs;}return {addLog,getLogs};
}
const logger = new Logger();
logger.addLog('First log message'); // Logged: First log message
logger.addLog('Second log message'); // Logged: Second log message
console.log(logger.getLogs()); // ['First log message', 'Second log message']

(四)继承和扩展

通过原型链实现继承,创建子类并继承父类的属性和方法。例如:

javascript">function Shape() {this.draw = function() {console.log('Drawing a shape.');};
}
function Circle(radius) {Shape.call(this);this.radius = radius;this.drawCircle = function() {console.log(`Drawing a circle with radius ${this.radius}.`);};
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
const circle = new Circle(5);
circle.draw(); // Drawing a shape.
circle.drawCircle(); // Drawing a circle with radius 5.

(五)事件处理和状态管理

管理状态和处理事件,如创建具有特定状态和事件处理方法的组件。例如:

javascript">function Button(text) {this.text = text;this.isPressed = false;this.clickHandler = function() {this.isPressed =!this.isPressed;console.log(`Button ${this.text} is ${this.isPressed? 'pressed' : 'released'}.`);};
}
const button = new Button('Click me');
button.clickHandler(); // Button Click me is pressed.
button.clickHandler(); // Button Click me is released.

六、构造函数的原型和原型链

每个构造函数都有一个 prototype 属性指向原型对象。原型上的属性和方法可被对象实例共享。例如:

javascript">function Person() {}
Person.prototype.sayHello = function() {console.log('Hello!');
};
const person1 = new Person();
const person2 = new Person();
person1.sayHello(); // Hello!
person2.sayHello(); // Hello!

原型链是 JavaScript 实现继承的机制,当访问对象的属性或方法时,若对象本身找不到,会沿着原型链向上查找,直到找到或到达顶端。例如:

javascript">function Animal() {}
Animal.prototype.sayHello = function() {console.log('Hello from Animal!');
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
const dog = new Dog();
dog.sayHello(); // Hello from Animal!

若这篇文章对你有启发,点赞可鼓励作者并让更多人看到,收藏以便随时查阅,关注作者能第一时间获取更多编程知识分享。让我们在编程海洋中探索进步,期待你的点赞、收藏和关注,携手书写精彩篇章!


http://www.ppmy.cn/ops/128133.html

相关文章

c++ pdf文件提取txt文本示例

最近抽空采用之前封装的接口将pdf文件提取出txt文本,顺利完成,界面如下所示: 提起的效果如下所示: 输出的txt文本内容如下: 下载链接:https://download.csdn.net/download/u011269801/89905548

线性可分支持向量机的原理推导 9-23拉格朗日乘子α的最大化问题 公式解析

本文是将文章《线性可分支持向量机的原理推导》中的公式单独拿出来做一个详细的解析,便于初学者更好的理解。 公式 9-23 是支持向量机(SVM)优化过程中从最大化问题到对偶问题的关键步骤之一。它将目标函数简化为关于拉格朗日乘子 α \alpha …

mac用户使用Windows的方法:虚拟机、远程桌面和迷你主机

🎉 前言 之前写了一篇博客,里面提到mac想要使用Windows系统可以使用远程桌面的方式连接服务器,今天不妨让我们把思路拓宽,看看还有哪些方法。 🎉 本质 我们通过远程桌面连接服务器,说到底不就是用本地电…

leetcode 3185. 构成整天的下标对数目 II 中等

给你一个整数数组 hours&#xff0c;表示以 小时 为单位的时间&#xff0c;返回一个整数&#xff0c;表示满足 i < j 且 hours[i] hours[j] 构成 整天 的下标对 i, j 的数目。 整天 定义为时间持续时间是 24 小时的 整数倍 。 例如&#xff0c;1 天是 24 小时&#xff0c…

Vue3 Echarts中国地图(包含轮播高亮区域)

vue3使用echarts去实现中国地图轮播高亮也是花了时间和精力的学习内容&#xff08;希望大家分享学习内容的时候 能够认真一点 不要贴一大堆代码上去 根本用不了 可以多写一些注释 谢谢。&#xff09; 我先直接贴代码 import { defineProps, ref, watch, onMounted, toRaw } fr…

在linux上部署ollama+open-webu,且局域网访问教程

在linux上部署ollamaopen-webu&#xff0c;且局域网访问教程 运行ollamaopen-webui安装open-webui &#xff08;待实现&#xff09;下一期将加入内网穿透&#xff0c;实现外网访问功能 本文主要介绍如何在Windows系统快速部署Ollama开源大语言模型运行工具&#xff0c;并使用Op…

GCC静态库与动态库链接顺序的深坑

有三个工程文件&#xff0c;A为SDL2动态库&#xff0c;B为基于A的静态库&#xff0c;C为基于A和B的主程序EXE&#xff0c;现在发现这个问题&#xff1a; 在C程序链接器命令的时候&#xff0c;通常像这种写法-lSDL2 -lLibB&#xff0c;此时就会报B报错找不到A中的函数&#xff…

Centos编写mysql备份脚本

1. 编写 MySQL 备份脚本 创建一个名为 backup.sh 的脚本&#xff0c;定期备份 fuint-food 数据库。 #!/bin/bash # 获取当前时间戳 TIMESTAMP$(date "%F-%H%M") # 备份存储路径 BACKUP_DIR"/path/to/backup/$TIMESTAMP" # MySQL 相关信息 MYSQL_USER&quo…