js内置函数的改写问题

2018-12-21  本文已影响0人  写代码的女孩最可爱

点这里先看看什么是js内置函数?

简单点说内置函数就是浏览器内核自带的函数,访问他的constructor属性时可以看到‘[ native code ]’ 字样的函数,举个例子在控制台打出:

alert.constructor
ƒ Function() { [native code] }

那么是不是只要函数的constructor属性包含native code字符串就表示函数没有被篡改过呢?
不是的,改写过后函数的constructor里面可以包含特征字符串
举个栗子:

console.log.constructor
ƒ Function() { [native code] }
Function.prototype.toString = function (){return 'function' + this.name + '() {       [native code] }'}
ƒ () {       [native code] }
console.log.constructor
ƒ Function() {       [native code] }
console.log('miao')
miao
console.log = function(){alert('miao')}
ƒ () {       [native code] }
console.log('jiujiu')
//页面上弹出框并显示‘miao’

常规的改写方式

var _alert = alert;
alert = function(a){
console.log('来了一次');
return _alert(a)
}

本身没有prototype的函数在改写之后就会有prototype属性,所以可以通过访问内置函数的prototype属性来判断函数是否被改写

alert.prototype 
undefined
var a = alert;
alert = function(y){
console.log('hdfjk');
return a(y);
};
alert.prototype 
{constructor: ƒ}

总结

要看(本身没有prototype的)函数是否被改写,可以通过查看其是否有prototyp;要看(本身有prototype的)函数是否被改写,可以直接将函数打出来比对正常值

上一篇 下一篇

猜你喜欢

热点阅读