「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」。
2.5 Object.prototype.toString() 判断数据类型
toString()是Object的原型方法,调用该方法,默认返回当前对象的[[Class]]。这是一个内部属性,其格式为[object Xxx],其中Xxx就是对象的类型。
对于Object对象,直接调用toString()就能返回[object Object],而对于其他对象,则需要通过call、apply来调用才能返回正确的类型信息。
var toString = Object.prototype.toString;
toString.call(123); //"[object Number]"
toString.call('abcdef'); //"[object String]"
toString.call(true); //"[object Boolean]"
toString.call([1, 2, 3, 4]); //"[object Array]"
toString.call({name:'wenzi', age:25}); //"[object Object]"
toString.call(function(){ console.log('this is function'); }); //"[object Function]"
toString.call(undefined); //"[object Undefined]"
toString.call(null); //"[object Null]"
toString.call(new Date()); //"[object Date]"
toString.call(/^[a-zA-Z]{5,20}$/); //"[object RegExp]"
toString.call(new Error()); //"[object Error]"
3. JS继承的实现方式
3.1 构造函数继承
-
先定义一个父构造函数
-
再定义一个子构造函数
-
子构造函数继承父构造函数的属性(使用call方法)
// 1. 父构造函数
function Father(uname) {
// this 指向父构造函数的对象实例
this.uname = uname;
}
// 2 .子构造函数
function Son(uname, age) {
// this 指向子构造函数的对象实例
//3.使用call方式实现子继承父的属性
Father.call(this, uname);
this.age = age;
}
var son = new Son('王帅帅', 18);
console.log(son);
3.2 原型对象继承方法
-
先定义一个父构造函数
-
再定义一个子构造函数
-
子构造函数继承父构造函数的属性(使用call方法)
-
设置子级的prototype原型对象
// 1. 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log(100000);
};
// 2 .子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
Father.call(this, uname, age);
this.score = score;
}
// Son.prototype = Father.prototype; 这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化
Son.prototype = new Father();
// 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
Son.prototype.constructor = Son;
// 这个是子构造函数专门的方法
Son.prototype.exam = function() {
console.log('孩子要考试');
}
var son = new Son('王帅帅', 18, 100);
console.log(son);
3.3 Object.create实现类式继承
Object.create(proto, [propertiesObject])
-
方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。返回在指定原型对象上添加新属性后的对象。
-
proto:新创建对象的原型对象。
-
propertiesObject:可选。需要传入一个对象,该对象的属性类型参照Object.defineProperties()的第二个参数。如果该参数被指定且不为 undefined,该传入对象的自有可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符。