示例

var teacher = {
	name: 'zhangsan',
  age: 32,
  sex: 'male',
  teach: function() {
  	console.log('I am teaching js');
  },
  smoke: function() {
    this.age--;
  	console.log('I am smoking');
  },
  eat: function(){
    this.age++;
  	console.log('I am having a dinner');
  }
}

// 查询属性
teacher.name;
teacher.teach();

// 新增属性
teacher.address = '北京';
teacher.drunk = function() {};

// 修改属性
teacher.age = 20;
teacher.eat = function() {};

// 删除属性
delete teacher.age;
delete teacher.teach;
var attendance = {
	students: [],
  join: function(name) {
  	this.students.push(name);
    console.log(this.students);
  },
  leave: function(name) {
    var idx = this.students.indexOf(name);
    if(idx !== -1){
    	this.students.splice(idx, 1);
    }
  }
}

创建方法

原型也是对象,原型的原型由 Object 构造而来

function Obj() {}
var obj = new Obj();

console.log(obj.__proto__ === Obj.prototype); // true
console.log(obj.__proto__.__proto__ === Object.prototype); // true
console.dir(obj.__proto__);

Untitled

new 做了什么

自己实现一个简化版的 new 操作符

function myNew(constructor, ...args) {
  // 创建一个新对象,并将其原型指向构造函数的 prototype
  const newObject = Object.create(constructor.prototype);
  
  // 使用新对象作为 this 执行构造函数
  const result = constructor.apply(newObject, args);
  
  // 如果构造函数显式返回了一个对象,则返回该对象,否则返回新创建的对象
  return (result && typeof result === 'object') ? result : newObject;
}

// 使用 myNew 创建 Person 对象
const person2 = myNew(Person, 'Bob', 25);
person2.sayHello(); // 输出: Hello, my name is Bob and I am 25 years old.

总结

new 操作符在 JavaScript 中主要用于创建并初始化新对象。它的主要作用是: