今天,同事(已经 从事前端开发4 年有余了,从一开始就是使用 vue 和 react ,结合着 webpack 写这个 ES6 相关的东西,很少接触到有关 ES6 之前的东西 的写法)问了我一个问题,说有一个东西不知道怎么去进行迁移(即看不懂),即类似于以下的这样的形式内容;
javascript">
function FunObj() { }
FunObj.prototype.getRandom = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
FunObj.prototype.getRandomColor = function () {
let r = this.getRandom(0, 256);
let g = this.getRandom(0, 256);
let b = this.getRandom(0, 256);
return "rgb(" + r + "," + g + "," + b + ")";
}
当我看到他问的这个问题的时候,我当时心里一惊,这不就是我们(我是 10 年开始接触前端14 年正式进入前端工作)曾经经常写的JavaScript 的对象定义么,他居然看不懂,后来一想也是,毕竟从他们出来,接触的东西,跟我们刚出来的时候接触的东西差别还是挺大的,就比如说 ES6 之前的对象定义、对象继承等等;其实也并非他们不努力,只是说接触的东西少,现在写的都现代化的一些东西。
接下来,我就简单的总结一下,如何在 JavaScript 中进行定义对象:
1. 对象字面量
这是最常见的方式,使用花括号 {}
定义对象,属性和方法用键值对表示。
const person = {
name: "Alice",
age: 25,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
console.log(person.name); // 输出: Alice
person.greet(); // 输出: Hello, my name is Alice
2. 使用 new Object()
通过 new Object()
创建对象,然后添加属性和方法。
const person = new Object();
person.name = "Bob";
person.age = 30;
person.greet = function() {
console.log("Hello, my name is " + this.name);
};
console.log(person.name); // 输出: Bob
person.greet(); // 输出: Hello, my name is Bob
3. 构造函数
通过构造函数创建对象,适合需要创建多个相似对象的场景。
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
}
const person1 = new Person("Charlie", 35);
const person2 = new Person("David", 40);
console.log(person1.name); // 输出: Charlie
person2.greet(); // 输出: Hello, my name is David
4. Object.create()
使用 Object.create()
基于现有对象创建新对象。
const personPrototype = {
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
const person = Object.create(personPrototype);
person.name = "Eve";
person.age = 28;
console.log(person.name); // 输出: Eve
person.greet(); // 输出: Hello, my name is Eve
5. ES6 类
使用 ES6 的 class
语法定义对象。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello, my name is " + this.name);
}
}
const person = new Person("Frank", 45);
console.log(person.name); // 输出: Frank
person.greet(); // 输出: Hello, my name is Frank
总结
- 对象字面量:简单直接。
new Object()
:较少使用。- 构造函数:适合创建多个相似对象。
Object.create()
:基于原型创建对象。- ES6 类:现代语法,适合复杂对象。
根据需求选择合适的方式。