构造函数和原型对象

1、构造函数和原型对象

1.1 概述

类是对象的模板,对象是类的实例,ES6之前没有类的概念,用构造函数来定义对象和它们的特征

创造对象三种方式:
1.对象字面量

let obj1 = {}

2.new Object()

let obj2 = new Object()

3.自定义构造函数

和 new 一起配合使用

//构造函数内部定义方法,会造成内存浪费
function Star(name,age) {
    
    
  this.name = name;
  this.age = age;
  this.sing = function() {
    
    
    console.log(this.name + " " + this.age);
  }
}
let ldh = new Star("刘德华",56);
ldh.sing(); //刘德华 56
1.2 实例成员与静态成员
  1. 实例成员:构造函数内部通过this添加的成员
    • this.namethis.agethis.sing 都是
    • 只能通过实例化的对象访问
  2. 静态成员:在构造函数本身上添加的成员
    • sex = "男",sex 就是静态成员
    • 只能通过构造函数访问Star.sex
1.3 原型对象 prototype

每一个构造函数都有一个 prototype 属性,指向一个对象。这个对象的所有属性和方法,都会被构造函数所拥有,可以把不变的方法定义在 prototype 对象上,这样所有对象实例都可以共享这些方法 //节约内存资源

function Star(name,age) {
    
    
   this.name = name;
   this.age = age;       
 }
Star.prototype.sing = function() {
    
    
  console.log(this.name + " " + this.age);
}
let ldh = new Star("刘德华",56);
let zxy = new Star("张学友",57);
console.log(ldh.sing === zxy.sing); //true
1.4 对象原型 __proto__

不是标准的W3C属性,实际开发中不能使用

每一个对象都有一个属性 __proto__属性,指向它的构造函数的原型对象 prototype

let ldh = new Star("刘德华",56);
ldh.sing // 指向 Star 的 prototype
console.log(ldh.__proto__ === Star.prototype) //true
1.5 constructor 构造函数

对象原型 __proto__和 原型对象 prototype 里都有一个 constructor 属性,指向构造函数本身。很多情况下手动设置 constructor 属性指回原来的构造函数

function Star(name,age) {
    
    
  this.name = name;
  this.age = age;       
}
Star.prototype = {
    
    
  constructor: Star, //指回Star,如果不加这句,那原来的constructor会被覆盖,指向一个新的Object(原型替换)
  sing: function() {
    
    
    console.log("我会唱歌");
  },
  movie: function() {
    
    
    console.log("我会演电影");
  }
}
let ldh = new Star("刘德华",56);
console.log(ldh.__proto__)  //Star(name,age){...}
console.log(Star.prototype) //Star(name,age){...}

2、函数对象的成员

函数也是对象

2.1__proto__

返回 Function.prototype

function test() {
    
    
  console.log('我是test函数');
}
console.log(test.__proto__ === Function.prototype); //true 

2.2 name

返回函数名

function test() {
    
    
  console.log('我是test函数');
}
console.log(test.name) //test

2.3 length

返回形参的长度

function f(num1,num2,num3,num4,num5){
  console.log(f.length);
}
f(10,20,30);  //5

2.4 caller

  • 如果fn2函数在fn1函数中被调用, 那fn2函数的caller就是fn1.

  • 如果fn2是直接调用的,没有在一个函数中调用,那fn2的caller就是null.

function fn1() {
    
    
  console.log('我是fn1函数');
  fn2();
}
function fn2() {
    
    
  console.log('我是fn2函数');
  console.log(fn2.caller);
}
fn1();// 返回fn1函数
fn2();// null

猜你喜欢

转载自blog.csdn.net/weixin_44257930/article/details/109100444