1.获取对象 obj 的所有属性(自有属性和继承属性),保存到数组 lst 中

//获取对象obj的所有属性(自有属性和继承属性),保存到数组lst 中
var lst = [];
function getAllAttrs(obj){
var arr = Object.getOwnPropertyNames(obj);
for(r in arr){
lst.push(arr[r]);
}
if(obj.__proto__ !== null){
obj = obj.__proto__;
getAllAttrs(obj);
}
}
getAllAttrs(obj);
console.log(lst);

2.实现一个完整的复数类

//实现一个完整的复数类: Complex

//定义构造函数
function Complex(real, imaginary){
if(isNaN(real) || isNaN(imaginary)) throw TypeError();
this.r = real;
this.i = imaginary;
};
// 定义非静态方法
Complex.prototype.add = function(that){
return new Complex(this.r+that.r,this.i+that.i);
};
Complex.prototype.mui = function(that){
return new Complex(this.r*that.r-this.i*that.i,this.r*that.r+this.i*that.i);
};
//取模运算
Complex.prototype.mag = function(){
return Math.sqrt(this.r*this.r+this.i*this.i);
};
Complex.prototype.neg = function(){
return new Complex(-this.r,-this.i);
};
Complex.prototype.toString = function(){
return "{"+this.r+", "+this.i+"}";
};
Complex.prototype.equals = function(that){
return that != null &&
that.constructor === Complex &&
this.r === that.r &&
this.i === that.i;
};
//定义类静态属性
Complex.ZERO = new Complex(,);
Complex.ONE = new Complex(,);
Complex.I = new Complex(,);
//定义类静态方法
Complex.parse = function(s){
try{
var m = Complex._format.exec(s);
return new Complex(parseFloat(m[]),parseFloat(m[]));
}catch(x){
throw new TypeError("Can't parse "+s+" as a complex number.");
}
};
//静态类属性
Complex._format = /^\{([^,]+),([^}]+)\}$/; //使用
var c = new Complex(,);
var d = new Complex(c.i,c.r);
console.log(c.add(d).toString()); // {5, 5}
console.log(Complex.parse(c.toString())); // Complex {r: 2, i: 3}
console.log(Complex.parse(c.toString()).add(c.neg()).equals(Complex.ZERO)); // true

3.判断鸭辩型

//判断鸭辩型
//如果 o 实现了除第一个参数之外的参数所表示的同名方法, 则返回true
function quacks3(o){
for(var i=;i<arguments.length;++i){//遍历o之后的所有参数
var arg = arguments[i];
switch(typeof arg){
case 'string': // 参数为string直接用名字检查
if(typeof o[arg] !== "function")
return false;
continue;
case 'function': // 参数为函数, 视为构造函数, 检查函数的原型对象上的方法
arg = arg.prototype; //进入下一个case
case 'object':
for(var m in arg){ //遍历对象的每个属性
if(typeof arg[m] !== 'function') //跳过不是方法的属性
continue;
if(typeof o[m] !== 'function')
return false;
} }
}
return true;
}
//说明: 只检测函数名,而不用管细节, 不是强制的API,因此满足鸭辩型的本质, 灵活
//限制: 不能用于内置类, 因为for/in不能遍历不可枚举的方法. 在ES5中可以使用Object.getOwnPropertyNames()
function quacks5(o){
for(var i=;i<arguments.length;++i){
var arg = arguments[i];
switch(typeof arg){
case 'string':
if(typeof o[arg] !== 'function')
return false;
continue;
case 'function':
arg = arg.prototype;
case 'object':
var props = Object.getOwnPropertyNames(arg.__proto__);
var props2 = Object.getOwnPropertyNames(arg);
for(var prop in props2){
props.push(props2[prop]);
}
for(var m in props){
if(props[m] !== 'function')
continue;
if(o[m] !== 'function')
return false;
}
}
}
return true;
};

4.合并多个对象属性

// 将变长参数sources对象的可枚举(for/in)属性合并到target中,并返回target
// target 的值是被修改的, 深拷贝(递归合并)
// 合并从左到右进行, 同名属性保持和左边一样(除非属性是空对象)
function myextend(target /*...sources*/){
if(!arguments.length)
return undefined;
if(arguments.length === )
return target;
for(var i=;i<arguments.length;++i){
var source = arguments[i];
for(var prop in source){
if(target.hasOwnProperty(prop) &&
target[prop] !== undefined &&
target[prop] != {}) // 目标对象上该属性存在且属性值不为undefined(可以为null)且不为空对象
continue;
if(typeof source[prop] === 'object'){
target[prop] = {};
target[prop] = myextend({},source[prop]);
}else{
target[prop] = source[prop];
}
}
}
return target;
}

测试:

// 结果在chrome console中查看
var target = {
t1:,
t2:{
t1:,
t2:{
t1:,
t2:"t2"
}
}
};
var source1 = {
s1:,
s2:{
s1:,
s2:{
s1:,
s2:"s2"
}
}
};
var source2 = {
r1:,
r2:{
r1:,
s2:{
r1:,
r2:"s2"
}
}
};
var t = myextend(target,source1,source2);
console.log(t);

5.为对象添加一个id属性

(function(){
Object.defineProperty(Object.prototype,"objectId",{
get: idGetter,
enumerable: false,
configurable: false
});
function idGetter(){
if(!(idprop in this)){
if(!Object.isExtensible(this))
throw Error("Can't define id for nonextensible objects");
Object.defineProperty(this,idprop,{
value: nextid++,
writable: false,
enumerable: false,
configurable: false
});
return this[idprop];
}
}
var idprop = "|***objectId*|";
var nextid = ;
})(); var obj = {};
console.log(obj.objectId); // 1

6.让函数既可以当成构造函数,也可以当成工厂方法调用

// 既可以当成构造函数用, 也可以当成工厂方法来用
function Range(from, to){
var props = {
from:{value:from,enumerable:true,writable:false,configurable:false},
to:{value:to,enumerable:true,writable:false,configurable:false}
};
if(this instanceof Range){ // 如果作为构造函数来调用的话
Object.defineProperties(this,props);
}else{ // 否则当成作为工厂方法来调用
return Object.create(Range.prototype,props);
}
}

持续更新中...

参考

1. <<JavaScript权威指南: 第6版>>


-->

JavaScript 代码小片段的更多相关文章

  1. jquery代码小片段

    1. 使用jQuery来切换样式表 //找出你希望切换的媒体类型(media-type),然后把href设置成新的样式表. $(‘link[media="screen"]‘).at ...

  2. Python代码小片段

    1.前面变量值的改变不影响后面变量的调用 index=1 index,a=2,index+1 print(a,index) #2 2 2.类的继承(子类实例如何调用父类同名方法) class a: d ...

  3. 实用的 CSS 小片段

    看了 30 Seconds CSS,有了许多收获,所以写下了这篇文章,算是收藏一些代码小片段,留作后用. 一.手写 Loading 动画 (1)弹性加载动画 CSS 代码如下: .bounce-loa ...

  4. 精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解!

    原文:https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates 作者:Chalaran ...

  5. 精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解

    原文:Chalarangelo  译文:IT168 https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with ...

  6. 精心收集的48个JavaScript代码片段,仅需30秒就可理解

    源文链接 :https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates 该项目来自于 G ...

  7. 编写JavaScript 代码的5个小技巧

    1.Array.includes 与条件判断 一般我们判断或用 || // condition function test(fruit) { if (fruit == "apple" ...

  8. 超实用的 JavaScript 代码片段( ES6+ 编写)

    Array 数组 Array concatenation (数组拼接) 使用 Array.concat() ,通过在 args 中附加任何数组 和/或 值来拼接一个数组. const ArrayCon ...

  9. 新书《编写可测试的JavaScript代码 》出版,感谢支持

    本书介绍 JavaScript专业开发人员必须具备的一个技能是能够编写可测试的代码.不管是创建新应用程序,还是重写遗留代码,本书都将向你展示如何为客户端和服务器编写和维护可测试的JavaScript代 ...

随机推荐

  1. centos7修改ssh默认登陆端口号

    参考网站; https://blog.csdn.net/ausboyue/article/details/53691953 第一步:修改SSH配置文件(注意是sshd_config而不是ssh_con ...

  2. Devexpress 百分号显示格式

    百分号:{0:P}表示显示为百分号模式.如数据源中为0.5.表示出来为50%

  3. xe DateTimePicker.Date bug

    xe6 bug xe7 ok DateTimePicker1->DateTime.DateString(); DateTimePicker1->DateTime.DateTimeStrin ...

  4. YII assets使用

    为什么用YII assets 1.assets的作用是方便模块化,插件化的,一般来说出于安全原因不允许通过url访问protected下面的文件 ,但是我们又希望将module单独出来,所以需要使用发 ...

  5. jsfl 第一天

    ctrl+f10,打开操作记录 通过打开到目标fla的舞台,然后运行写好的jsfl,默认就以目标fla为调试对象. 通过name可以获取层名字,帧标签,元件实例名等,name属性要根据对象的应用而产生 ...

  6. ABAP-BarCode-3-调用第三方控件BarTender实现打印

    1.BarTender软件安装及注册 2.BarTender设置好打印模板 3.ABAP生成TXT文件放置FTP服务器指定文件夹 4.BarTender轮询FTP服务器文件夹中的TXT,并按照模板打印 ...

  7. mongodb基础学习7-备份与恢复

    下面来讲讲mongodb的备份与恢复 备份可以备份为二进制格式,如果是用于数据交换,可以备份成json或cvs格式 导入/导出可以操作的是本地的mongodb服务器,也可以是远程的. 所以,都有如下通 ...

  8. 初始化centoS 相关

    install aspnetcoremodule for iis https://docs.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=as ...

  9. 3类与对象——重拾Java

    面向对象编程的3个特性 1 封装性 面向对象编程核心思想之一就是将数据和对数据的操作封装在一起.通过抽象,即从具体的实例中抽取共同的性质形成一般的概念,比如类的概念. 在实际生活中,我们每时每刻都在与 ...

  10. Redis 发布与订阅 消息

    基于Redis消息队列-实现短信服务化 1.Redis实现消息队列原理 常用的消息队列有RabbitMQ,ActiveMQ,个人觉得这种消息队列太大太重,本文介绍下基于Redis的轻量级消息队列服务. ...