相信jser兄弟们肯定会碰到这样一个问题, 在做数组类的操作的时候,会要求删除数组中的一个元素:亦或是判断某值是否存在于这个数组: OK,拿删除数组元素举例,扩展方法为: Array.prototype.remove = function(val){ var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); } } 很简单了扩展了一个删除元素的方法,那么我说的坑是什么呢? 在我们使用for··in 遍历对象的时…
一.for in 1.使用 for in 循环遍历对象的属性时,原型链上的所有属性都将被访问: Object.prototype.say="cgl"; // 修改Object.prototype   var person ={ age: 18 }; for (var key in person) { console.log(key, person[key]);//这里用person.key得不到对象key的值,用person[key] 或者 eval("person.&quo…
数组去重(要求:原型链上添加函数) <script> //数组去重,要求:在原型链上添加函数 //存储不重复的--仅循环一次 if(!Array.prototype.unique1){ Array.prototype.unique1=function(){ var item , hash={}, len=this.length, result=[]; for(var i = 0 ; i < len ; i++){ item = this[i]; if(!hash[item+Object.…
在刚刚接触JS原型链的时候都会接触到一个熟悉的名词:prototype:如果你曾经深入过prototype,你会接触到另一个名词:__proto__(注意:两边各有两条下划线,不是一条).以下将会围绕prototype和__proto__这两个名词解释为什么不能在原型链上使用对象以及JS原型链的深层原理. 一.为什么不能在原型链上使用对象: 先举一个非常简单的例子,我有一个类叫Humans(人类),然后我有一个对象叫Tom(一个人)和另一个对象叫Merry(另一个人),很明显Tom和Merry都…
1. Object.prototype.toString.call(value) // 返回数据的类型 // "[object Object]" 等 2. Array.prototype.slice.call(value) // 将类数组,转为真正的数组 例如: Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 } --> [a, b] Array.prototype.slice.call(document.queryS…
关于javascript的原型链有一个问题我一直很疑惑:为什么 Function instanceof Object 与 Object instanceof Function都为true呢? Function instanceof Object // ->trueObject instanceof Function // ->true12先给个结论吧(函数a和对象b指什么看下去就直到了):Object instanceof Function的实质就是函数a在Object的原型链上:Functi…
<script> //1.在我们之前的项目里向原型链中集成方法时大多代码分析不严密,有时间我在这里会做详细分析; Array.prototype.each = function(fn) { try { this.i || (this.i = 0); //在这里,fn.constructor === Function保证了输入的构造类型 if (this.length > 0 && fn.constructor === Function) { while (this.i &…
承接上文,下面是第四个案例 附上项目链接: https://github.com/wesbos/JavaScript30 const inventors = [ { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 }, { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 }, { first: 'Galileo', last: 'Galilei', year:…
遇到一个面试题 要求写一个函数A,每次进行new操作时候能输出2,3,4,5... new A() // 输出2 new A() // 输出3 new A() // 输出4 function A() { this.a++ console.log(this.a) } A.prototype.a = 1 这样写是错误的,因为实例化对象中的a属性并不是原型上的引用,而是把原型上的a给拷贝了一份给a. 所以这样每次输出都是2. 正确答案: function A() { this.__proto__.a+…
语法:父对象.prototype.isPrototypeOf(子对象) 代码栗子: function Student(){ this.name = "小马扎"; ; } var sky = new Student(); var img = new Image(); console.log(Student.prototype.isPrototypeOf(sky)); // true console.log(Student.prototype.isPrototypeOf(img)); //…