实用技巧
使用闭包实现私有变量
function Person(name, age) {
this.getName = function() { return name; };
this.setName = function(newName) { name = newName; };
this.getAge = function() { return age; };
this.setAge = function(newAge) { age = newAge; };
//未在构造函数中初始化的属性
var occupation;
this.getOccupation = function() { return occupation; };
this.setOccupation = function(newOcc) { occupation =
newOcc; };
}
创建对象的构造函数
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
判断对象的数据类型
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target);
const isArray = isType('Array');
console.log(isArray([]));
使用Object.prototyoe.toString
配合闭包,通过传入不同的判断类型,返回不同的判断函数。
不推荐将这个函数用来检测可能会产生包装类型的基本数据类型上,因为
call
会将第一个参数进行装箱操作。
循环实现数据map
方法
使用reduce
实现数组map
方法
循环实现数组filter
方法
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。