构造函数

错误之处,欢迎指正。


1. 构造函数的特性

  1. 通常使用大驼峰命名法来命名一个构造函数(普通函数使用小驼峰命名法)。
  2. 使用new关键字来使用构造函数,此时构造函数会默认返回一个对象,并且此时构造函数里面的this指向返回的这个对象。
function Person(name) {
    this.name = name;
}
const obj = new Person('chris');
console.log(obj);  
控制台输出结果
  1. 如果在构造函数中添加return并且是一个原始值,那么不会有任何影响,构造函数依然返回构造的对象;如果是一个引用值,那么构造函数会返回这个引用值。
  2. 如果使用new关键字使用构造函数,此时new.target是该函数体,如果不是使用newnew.targetundefined。可以用来检测是否是用new关键字使用构造函数。
  3. 对象都是通过构造函数构造出来的。
const obj = {
    name: 'chris'
}

诸如我们平时的声明一个对象的写法,其实是一种语法糖,实际上:

const obj = new Object();
obj.name = 'chris';

实际上function也是通过构造函数Function构造出来的,函数字面量的写法也属于一种语法糖。那么实际上可以有这样的关系:Function构造一个构造函数,构造函数产生对象。

  1. 为了增强原始类型的功能,javascript创建了BooleanNumberString三个构造函数。当把一个原始类型当对象使用时,javascript就会自动new 构造函数()来调用属性。
const id = 123.123;
console.log(id.toFixed(2));  //123.12 实际上:
console.log(new Number(id).toFixed(2));  //123.12  构造函数返回对象,对象上面有属性
  1. 实例/成员属性,通过构造函数创建的对象调用的属性。
function Person() {
    this.name = 'chris';
}
const me = new Person();
console.log(me.name);  //chris 实例属性

function的实例方法call

function test() {
    console.log(this.chris);
} 
test();  //this指向window 输出undefined
const testObj = {
    chris: 'handsome'
}
test.call(testObj);  //handsome

call方法调用一个函数时,可以改变函数中this的指向,如上述例子中,用calltest函数中的this指向testObj
callapply的区别就在于传参方式不同。

function test(chris, age) {
    console.log(chris);
    console.log(age);
}
const testObj = {};
test.apply(testObj, ['handsome', 22]);  //handsome 22
test.call(testObj, 'handsome', 23);  //handsome 23

apply传参时要放在数组里面。
bind用法:

function test(chris, age) {
    console.log(chris);
    console.log(age);
}
const testObj = {};
const newFunc = test.bind(testObj, 'handsome', 22); 
newFunc(); //handsome 22
newFunc(); //handsome 22

通常用call或者apply来将一个类数组转换成数组:

function test() {
    console.log(arguments);  //类数组
    console.log(Array.isArray(arguments));  //false  用Array构造函数的静态方法判断arguments是不是数组
    const newArr = Array.prototype.slice.call(arguments); //调用Array原型上的slice方法,并且此时this指向arguments,不传参就代表不截取,返回完整数组。
    console.log(Array.isArray(newArr));  //true
    console.log(newArr); //[1,2,3,4,5]
}
test(1,2,3,4,5);
  1. 静态属性是指通过构造函数调用的属性。
function Person() {}
Person.type = 'human';
const me = new Person();
console.log(Person.type);  //human  静态属性
console.log(me.type);  //undefined

Object的静态属性:

function Person(name, age) {
    this.name = name;
    this.age = age
}
const me = new Person('chris', 22);
console.log(Object.keys(me));  //["name", "age"]
console.log(Object.values(me));  //["chris", 22]
console.log(Object.entries(me));  //[["name", "chris"], ["age", 22]]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容