每当我拨打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)
答案 0 :(得分:4)
第一个代码段正在扩展Array
原型而不是Object
。由于replace
是Object
的一个实例,因此您应该这样做:
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
&#13;
答案 1 :(得分:0)
您正在扩展数组原型,而不是对象原型
将其更改为:
Object.prototype.arrayGuide = function () {
console.log(this);
}
...也
永远不会扩展原生对象的原型,除非它是polyfill