gpt4 book ai didi

javascript - [需要澄清]如何在探索原型(prototype)属性时处理类型错误

转载 作者:行者123 更新时间:2023-11-28 07:01:51 25 4
gpt4 key购买 nike

我想编写一个函数来列出对象及其原型(prototype)的所有可用属性(区分函数和其余属性),以了解如何操作该对象。

问题:无法访问某些!现有的!对象的属性,请参阅帖子末尾的示例代码,因为代码抛出如下类型错误:“TypeError:在未实现接口(interface) [...] 的对象上调用了 [...] getter”。

以下示例的确切错误代码:“TypeError:在未实现接口(interface) EventTarget 的对象上调用了‘ownerGlobal’ getter。”奇怪的是属性和 get&set 函数存在,请参阅:http://postimg.org/image/sh1okt4g7/ + console.log("属性存在:"+obj.hasOwnProperty(oneElem)); 打印 true。

在研究这个问题时,我发现了这篇文章:can't read Element.prototype in firefox .

据我了解,所有类型错误都来自这样一个事实:原型(prototype)链中的不同 objectPrototypes 没有可访问的值,因为它们是原型(prototype)并且没有“真实”对象。 因此,所有抛出 TypeErrors 的属性都应该被丢弃,因为它们无法被使用。是这样吗?
另一方面,可以安全地假设所有剩余的属性都可以使用(调用函数、读取值),尽管它们是由原型(prototype)对象定义的?

<小时/>

源代码:
- 没那么有趣,但如果有人想测试一下,请随意
- 创建一个新的 Firefox 插件 (developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Getting_Started_(jpm)),复制并粘贴代码并运行插件

var mtabs = require("sdk/tabs");
//mtabs.open("http://lolvideoslol.tumblr.com/post/124427537261/lani-p-the-amount-of-pressure-put-on-the-last"); //open tab
mtabs.on('pageshow', newTabLoaded); //add listener
var { viewFor } = require("sdk/view/core"); //convert to low lvl to get document


function newTabLoaded(tabHigh) {
//get website doc
var document = viewFor(tabHigh.window).top.gBrowser.getBrowserForTab(viewFor(tabHigh)).contentDocument;
var nodeList = document.querySelectorAll("div[class^='video']"); //get interesting elements
analysePrototypeChain(nodeList[0]); //analyse the first element
//for (let i = 0, len = nodeList.length; i < len; i++) {
// analysePrototypeChain(nodeList[i]); //analyse the elements
//}
}

/**
* Prints the prototype chain and functions/other properties for the given object.
*
* @param {Object} obj to process.
*/
function analysePrototypeChain(obj) {
console.log("##############################################################");
console.log("######## checking prototypeChain for:", obj, "########");
let formatOptions = {"newLines": 0, "toString": 1};
printPrototypeChain(obj, [], formatOptions);
console.log();
let protos = getPrototypeChain(obj, []);

for (let i = 0, len = protos.length; i < len; i++) {
if (protos[i] == "[object EventTargetPrototype]") {
console.log("_"+i+":", protos[i]);
printProperties(protos[i]);
}
}
console.log("##############################################################");

}


/**
* Prints the complete prototype chain for the given object.
*
* @param {Object} obj to process.
* @param {Array} stringArr must be empty when first called.
* @param {Object} formatOptions to control the formatting of the output.
* let formatOptions = {"newLines": 0, "toString": 1};
*/
function printPrototypeChain(obj, stringArr, formatOptions) {
if (stringArr.length === 0) {
if (formatOptions.toString === 1) {
stringArr.push(obj+"");
} else {
stringArr.push(obj);
}
}

let proto = Object.getPrototypeOf(obj);
if (proto === null || proto === undefined) {
if (formatOptions.newLines === 1) {
stringArr.push("\n\n->");
} else {
stringArr.push("->");
}

if (formatOptions.toString === 1) {
stringArr.push(proto+"");
} else {
stringArr.push(proto);
}
console.log.apply(console, stringArr);

} else {
if (formatOptions.newLines === 1) {
stringArr.push("\n\n->");
} else {
stringArr.push("->");
}

if (formatOptions.toString === 1) {
stringArr.push(proto+"");
} else {
stringArr.push(proto);
}
return printPrototypeChain(proto, stringArr, formatOptions);
}
}

/**
* Returns all prototypes in the prototype chain for the given object.
*
* @param {Object} obj to process.
* @param {Array} stringArr must be empty when first called.
* @returns {Array} Array with the determined prototypes.
*/
function getPrototypeChain(obj, stringArr) {
if (stringArr.length === 0) {
stringArr.push(obj)
}

let proto = Object.getPrototypeOf(obj);
if (proto === null || proto === undefined) {
stringArr.push(proto);
return stringArr;
} else {
//if (proto == "[object EventTargetPrototype]") {
// Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).forEach(function(val, idx, array) {
// console.log(val + ' -> ' + obj[val]);
// });
//}
stringArr.push(proto);
return getPrototypeChain(proto, stringArr);
}
}


/**
* Checks the given object for functions and other properties and prints them.
*
* @param {Object} obj to process.
*/
function printProperties(obj) {
if (obj === undefined || obj === null || obj === NaN) {
console.log(+"\n"+obj+" has no properties.");
return;
}
//for further usage
let functionList = [];
let remainingPropertiesList = [];
//output Strings
let functionString = "";
let remainingPropertiesString = "";
//checks all properties and fills functionList and remainingPropertiesList before invoking the next instruction
Object.getOwnPropertyNames(obj).forEach(checkElem);


console.log("Properties for:",obj+"");
let functionListLength = functionList.length;
if (functionListLength > 0) {
for (let i = 0, l = functionList.length-1; i < l; i++) {
functionString += functionList[i].type+" "+functionList[i].name+"(), ";
}
functionString += functionList[functionList.length-1].type+" "+functionList[functionList.length-1].name+"()";
}

let remainingPropertiesListLength = remainingPropertiesList.length;
if (remainingPropertiesListLength > 0) {
for (let i = 0, l = remainingPropertiesList.length-1; i < l; i++) {
remainingPropertiesString += "["+remainingPropertiesList[i].type+" "+remainingPropertiesList[i].name+"], ";
}
remainingPropertiesString += "["+remainingPropertiesList[remainingPropertiesList.length-1].type+" "+
remainingPropertiesList[remainingPropertiesList.length-1].name+"]";
}

console.log(">>>"+functionList.length+" functions:\n"+functionString);
console.log(">>>"+remainingPropertiesList.length+" remainingProperties:\n"+remainingPropertiesString);


//iterates through all properties to determine their type
function checkElem(oneElem, pos, arr) {
console.log("pos: "+pos+" at "+obj+" is: "+oneElem); //actual pos at the encolsing object
try {
if ((typeof obj[oneElem]) === 'function') {
functionList.push({type: (typeof obj[oneElem]), name: oneElem});
} else {
remainingPropertiesList.push({type: (typeof obj[oneElem]), name: oneElem});
}
} catch (e) {
console.log("<<<<<<<error while accessing "+oneElem);
console.log("property exists: "+obj.hasOwnProperty(oneElem));
}
}
}

最佳答案

As I understand it all the typeErrors came from the fact that the different objectPrototypes in the prototype chain have no accessible values, because they are prototypes and no "real" objects.

是的,原型(prototype)属性不应该在原型(prototype)对象本身上调用,而应该在通过构造函数创建的具体实例上调用。

正如您在屏幕截图中看到的那样,ownerGlobal 不是一个值属性,它是一个 getter,因此是一个以原型(prototype)作为 this 对象调用的函数,getter 函数并不是为此而设计的。

你能做的就是获取 property descriptor在原型(prototype)上:

Object.getOwnPropertyDescriptor(somePrototype, propertyName),然后就可以提取getter函数和 apply它到一个实例

关于javascript - [需要澄清]如何在探索原型(prototype)属性时处理类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32069185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com