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. HTML5 Canvas ( 线性渐变, 升级版的星空 ) fillStyle, createLinearGradient, addColorStop

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. 4. mybatis实战教程(mybatis in action)之四:实现关联数据的查询

    转自:https://www.cnblogs.com/shanheyongmu/p/5653599.html 有了前面几章的基础,对一些简单的应用是可以处理的,但在实际项目中,经常是关联表的查询,比如 ...

  3. 使用MATPLOTLIB 制图(散点图,热力图)

    import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('D:\\myfil ...

  4. HibernateTemplate使用注意点

    1.  findByExample(vo) 可轻松根据vo的内部数据作为参数查找数据,vo中的基本类型不能为null,同时不支持主键查找. 2. get(vo.class, id) 根据主键来查找数据 ...

  5. Redis基本操作-list

    Redis的5种数据结构:string.list.hash.set和zset; Redis 所有的数据结构都是以唯一的 key 字符串作为名称,然后通过这个唯一 key 值来获取相应的 value 数 ...

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

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

  7. .Net 常用开发工具

    ,net常用开发工具 LinqPad使用 LinqPad连接Oracle 使用 LINQPad 将linq转换为 lambda表达式 或者 SQL语句 LINQPad 4 初次使用心得 一.双击 二. ...

  8. Json字符串转Dictionary

    /// <summary> /// json字符串转Dictionary /// </summary> /// <param name="json"& ...

  9. binlog、redo log、undo log区别

    root@(none) 04:17:18>show variables like 'innodb_log_group_home_dir';+--------------------------- ...

  10. scrollTop实现图像循环滚动(实例1)

    <html><head><title>scrollTop实现图像循环滚动(实例1)</title><meta http-equiv="C ...