相关文章
prototype constructor __prpto__ 三者之间关系
好玩的:
1.字符串函数扩展 ( 一般调用 )
String.prototype.repeat=function(num){
return (new Array(num+1)).join(this)
}
console.log('good'.repeat(3))
2. 自定义原型名称 ( 配置调用 )
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
};
return this;
}
// 取整
Number.method("absolute", function () {
return Math[this < 0 ? "ceil" : "floor"](this);
});
console.log((-3.53).absolute());
// 移除字符串末端空白
String.method("trim", function () {
return this.replace(/^s+|s+$/g, '');
})
console.log(" meat ".trim());
继承
function Animal() { this.eye = 'two' this.foot = 'four' } function Cat(){ // Animal.call(this) Animal.apply(this,arguments) } // Cat.prototype = Animal.prototype - only prototype && diff by Animal.prototype // function Cat(){} // Cat.prototype = new Animal() // Cat.prototype.constructor = Cat // function Cat(){} // function F(){} // F.prototype = new Animal() // F.prototype = Animal.prototype // Cat.prototype = new F() // Cat.prototype.constructor = Cat // function Cat(){} // var ani = new Animal() // for(var i in ani){ // Cat.prototype[i] = ani[i] // } // function deepCopy(p, c) { // var c = c || {}; // for (var i in p) { // if (typeof p[i] === 'object') { // c[i] = (p[i].constructor === Array) ? [] : {}; // deepCopy(p[i], c[i]); // } else { // c[i] = p[i]; // } // } // return c; // } // deepCopy(new Animal(), Cat.prototype) console.log(new Animal()) console.log(new Cat(), new Cat().eye)