2017-10-06 68 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); 
} 

還...

,除非它是一個填充工具