javascript 代码片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 代码片段相关的知识,希望对你有一定的参考价值。
// apply 的模拟实现
Function.prototype.apply = function(context, arr) {
var context = Object(context) || window;
context.fn = this;
var result;
if (!arr) {
result = context.fn();
} else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push("arr[" + i + "]");
}
result = eval("context.fn(" + args + ")");
}
delete context.fn;
return result;
};
// call 的模拟实现
Function.prototype.call2 = function(context) {
var context = context || window;
context.fn = this;
var args = [];
for (var i = 1, len = arguments.length; i < len; i++) {
args.push("arguments[" + i + "]");
}
var result = eval("context.fn(" + args + ")");
delete context.fn;
return result;
};
// 测试一下
var value = 2;
var obj = {
value: 1
};
function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
};
}
bar.call(null); // 2
console.log(bar.call2(obj, "kevin", 18));
// 1
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }
// bind 的模拟实现
Function.prototype.bind2 = function(context) {
if (typeof this !== "function") {
throw new Error(
"Function.prototype.bind - what is trying to be bound is not callable"
);
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
var fNOP = function() {};
var fBound = function() {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(
this instanceof fNOP ? this : context,
args.concat(bindArgs)
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
// new 的模拟实现
function objectFactory() {
var obj = new Object(),
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var ret = Constructor.apply(obj, arguments);
return typeof ret === "object" ? ret : obj;
}
// 利用发布订阅模式,实现一个简单的数据绑定
function DataBinder(object_id) {
// Create a simple PubSub object
var pubSub = {
callbacks: {},
on: function(msg, callback) {
this.callbacks[msg] = this.callbacks[msg] || [];
this.callbacks[msg].push(callback);
},
publish: function(msg) {
this.callbacks[msg] = this.callbacks[msg] || [];
for (var i = 0, len = this.callbacks[msg].length; i <= len; i++) {
this.callbacks[msg][i].apply(this, arguments);
}
}
},
data_attr = "data-bind-" + object_id,
message = object_id + ":change",
changeHandler = function(evt) {
var target = evt.target || evt.srcElement, // IE8 compatibility
prop_name = target.getAttribute(data_attr);
if (prop_name && prop_name !== "") {
pubSub.publish(message, prop_name, target.value);
}
};
// Listen to change events and proxy to PubSub
if (document.addEventListener) {
document.addEventListener("change", changeHandler, false);
} else {
// IE8 uses attachEvent instead of addEventListener
document.attachEvent("onchange", changeHandler);
}
// PubSub propagates changes to all bound elements
pubSub.on(message, function(evt, prop_name, new_val) {
var elements = document.querySelectorAll("[" + data_attr + "=" + prop_name + "]"),
tag_name;
for (var i = 0, len = elements.length; i <= len; i++) {
tag_name = elements[i].tagName.toLowerCase();
if (tag_name === "input" || tag_name === "textarea" || tag_name === "select") {
elements[i].value = new_val;
} else {
elements[i].innerHTML = new_val;
}
}
});
return pubSub;
}
function Node(element) {
this.element = element;
this.next = null;
}
function LinkedList() {
this._head = new Node("This is Head Node.");
this._size = 0;
}
LinkedList.prototype.display = function() {
var currNode = this.getHead().next;
while (currNode) {
console.log(currNode.element);
currNode = currNode.next;
}
};
LinkedList.prototype.remove = function(item) {
if (item) {
var preNode = this.findPre(item);
if (preNode == null) return;
if (preNode.next !== null) {
preNode.next = preNode.next.next;
this._size--;
}
}
};
LinkedList.prototype.add = function(item) {
this.insert(item);
};
LinkedList.prototype.insert = function(newElement, item) {
var newNode = new Node(newElement);
var finder = item ? this.find(item) : null;
if (!finder) {
var last = this.findLast();
last.next = newNode;
} else {
newNode.next = finder.next;
finder.next = newNode;
}
this._size++;
};
/*********************** Utility Functions ********************************/
LinkedList.prototype.findLast = function() {
var currNode = this.getHead();
while (currNode.next) {
currNode = currNode.next;
}
return currNode;
};
LinkedList.prototype.findPre = function(item) {
var currNode = this.getHead();
while (currNode.next !== null && currNode.next.element !== item) {
currNode = currNode.next;
}
return currNode;
};
LinkedList.prototype.find = function(item) {
if (item == null) return null;
var currNode = this.getHead();
while (currNode && currNode.element !== item) {
currNode = currNode.next;
}
return currNode;
};
var attributions = {}
function get(that, key) {
return attributions[that] && attributions[that][key]
}
function set(that, key, value) {
if(!attributions[that]) attributions[that] = {}
attributions[that][key] = value
}
class MyClass {
set() {
set.apply(this, 'name', "cpf")
}
get() {
let name = get.apply(this, 'name')
console.log(name)
}
}
var events = {}
var data = {}
class MyClass {
on(event, handler) {
if(!events[event]) events[event] = []
events[event].push(handler)
}
trigger(event, params = []) {
let evts = events[event]
if(Array.isArray(evts)) evts.forEach(callback => {
if(typeof callback === 'function') {
if(Array.isArray(params)) callback.apply(this, params)
else callback.call(this, params)
}
})
}
get(key) {
return data[this] && data[this][key]
}
set(key, value, notify = true) {
if(!data[this]) data[this] = {}
data[this][key] = value
if(notify) {
this.trigger('change:' + key, value)
}
}
call(factory, ...args) {
factory.apply(this, args)
}
}
debounce = (fn, delay) => {
let timer;
return () => {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay);
}
}
throttle = (fn, threshhold = 250) => {
let last
let timer
return ()=> {
let now = +new Date()
if (last && now < last + threshhold) {
clearTimeout(timer)
timer = setTimeout(() => {
last = now
fn.apply(this, arguments)
}, threshhold);
} else {
last = now
fn.apply(context, args)
}
}
}
以上是关于javascript 代码片段的主要内容,如果未能解决你的问题,请参考以下文章