2017-10-06 63 views
1

问题

每当我打电话arrayGuide我得到一个error如何通过原型传递多维数组?

Array.prototype.arrayGuide = function() { 
 
    console.log(this) // When called… this should be getting logged. 
 
} 
 
//How to get this prototype to work 
 

 

 
replace = { 
 
    basic: { 
 
    stage1: { 
 
     one: ["hello", "world"], 
 
     two: ["brother", "sister"], 
 
     three: ["baby", "adult"] 
 
    }, 
 
    stage2: { 
 
     one: ["1"], 
 
     two: ["2"], 
 
     three: ["3"] 
 
    } 
 
    }, 
 
    advanced: { 
 
    humans: [/^biology\s/gi, /science$/i] 
 
    } 
 
} 
 

 
replace.arrayGuide() // This keeps throwing an error message
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



结果我应该得到

我应该从第一个演示中获得这些结果。但由于某种原因,我不是。

function arrayRegExpCreator(place) { 
 
    console.log(place) // I should be getting this… 
 
} 
 

 
replace = { 
 
    basic: { 
 
    stage1: { 
 
     one: ["hello", "world"], 
 
     two: ["brother", "sister"], 
 
     three: ["baby", "adult"] 
 
    }, 
 
    stage2: { 
 
     one: ["1"], 
 
     two: ["2"], 
 
     three: ["3"] 
 
    } 
 
    }, 
 
    advanced: { 
 
    humans: [/^biology\s/gi, /science$/i] 
 
    } 
 
} 
 

 
arrayRegExpCreator(replace)

回答

4

第一代码段延伸Array原型不Object。由于replaceObject的一个实例,你应该这样做:

Object.prototype.arrayGuide = function() { 
    console.log(this) // When called… this should be getting logged. 
} 

Object.prototype.arrayGuide = function() { 
 
    console.log(this) // When called… this should be getting logged. 
 
} 
 
//How to get this prototype to work 
 

 

 
replace = { 
 
    basic: { 
 
    stage1: { 
 
     one: ["hello", "world"], 
 
     two: ["brother", "sister"], 
 
     three: ["baby", "adult"] 
 
    }, 
 
    stage2: { 
 
     one: ["1"], 
 
     two: ["2"], 
 
     three: ["3"] 
 
    } 
 
    }, 
 
    advanced: { 
 
    humans: [/^biology\s/gi, /science$/i] 
 
    } 
 
} 
 

 
replace.arrayGuide() // This keeps throwing an error message

+2

值得一提的是,原生对象的原型是不能修改的从未延长原生对象的原型,如果它不是一个填充工具 – Voreny

0

你是在扩展阵列的原型,而不是对象原型

将其更改为:

Object.prototype.arrayGuide = function() { 
    console.log(this); 
} 

还...

,除非它是一个填充工具