复习-JS(3)-原型链

66 阅读2分钟

复习-JS(3)

1.原型对象

1.1什么是原型对象

原型对象是一个普通的对象,它包含了共享属性和方法,可以被其他对象继承和共享

每个JavaScript对象都有一个隐藏的内部属性[[Prototype]](可以通过__proto__Object.getPrototypeOf()访问),它指向该对象的原型对象。当我们访问一个对象的属性或方法时,如果对象本身没有这个属性或方法,JavaScript会自动去原型对象中查找,直到找到该属性或方法或者达到原型链的末端。

原型对象的主要作用是实现对象之间的继承。当我们创建一个对象时,JavaScript引擎会自动为其关联一个原型对象。我们可以使用构造函数、字面量语法或Object.create()方法来创建对象,并通过修改原型对象来实现继承。

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

Person.prototype.greet = function() {
  console.log('Hello, my name is ' + this.name);
};

var john = new Person('John', 25);
john.greet(); // 输出:Hello, my name is John

1.2 检测属性

用in检查对象中是否对象的属性时。如果对象中没有但原型对象有,也会返回true 例: console.log('name' in obj );

使用对象的hasOwnproperty()来检查对象自身是否有该属性

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));
// Expected output: true

console.log(object1.hasOwnProperty('toString'));
// Expected output: false

console.log(object1.hasOwnProperty('hasOwnProperty'));
// Expected output: false

1.3 instanceof

object instanceof constructor

var arr = [1, 2, 3];
console.log(arr instanceof Array); // 输出:true

1.4 看懂这张图片你就懂了

探索instanceof.png

2.数组

2.1改变原数组的方法

push

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // 输出:[1, 2, 3, 4]

pop

const arr = [1, 2, 3];
const lastValue = arr.pop();
console.log(lastValue); // 输出:3
console.log(arr); // 输出:[1, 2]

shift

const arr = [1, 2, 3];
const firstValue = arr.shift();
console.log(firstValue); // 输出:1
console.log(arr); // 输出:[2, 3]

unshift

const arr = [1, 2, 3];
arr.unshift(0, -1);
console.log(arr); // 输出:[-1, 0, 1, 2, 3]

splice

const arr = [1, 2, 3];
const deleted = arr.splice(1, 1, 4, 5);
console.log(deleted); // 输出:[2]
console.log(arr); // 输出:[1, 4, 5, 3]

reverse

const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // 输出:[3, 2, 1]

sort

const arr = [3, 1, 4, 2];
arr.sort();
console.log(arr); // 输出:[1, 2, 3, 4]