добавить в цепочку прототипов объекта {} функцию
Добрый вечер всем.
возник у меня глупый вопрос который ни как не могу реализовать. как добавить глобально в цепочку прототипов объектов конкретно {}, что бы к примеру был результат при: const obj = {a:1} console.log(obj) //{a:1} -> __proto__ -> myProtoFunction: f() const arr = [1,2,3] console.log(arr) //[1,2,3] -> ... -> в цепочке прототипов myProtoFunction() не имеется //и так с остальными конструкциями я пытался сделать следующим образом: Object.defineProperty(Object.prototype, 'isObject', { value: function() { if(!Boolean(this instanceof Array) && typeof this === 'object' && this !== null && this !== undefined){ return true }else{ return false } }, enumerable: false }); но проблема в том, что все в js это объекты, и если вызвать массив, то в цепочке прототипов окажется моя функция 'isObject'. надеюсь объяснил корректно, хотелось бы услышать какие-нибудь варианты и решения данной задачи. Заранее спасибо |
взял здесь - https://developer.mozilla.org/en-US/...rototype_chain
... Performance The lookup time for properties that are high up on the prototype chain can have a negative impact on the performance, and this may be significant in the code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain. ... Bad practice: Extension of native prototypes One misfeature that is often used is to extend Object.prototype or one of the other built-in prototypes. This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality. ... In conclusion It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features. ... const obj = { a: 1 } function myFoo() { console.log(this.a) } const myFooInstance = myFoo.bind(obj) myFooInstance() myFoo.call(obj) myFoo.apply(obj) ) не ответ на конкретный вопрос... |
Можно поставить геттер и проверять что прототип - прототип объекта. Но это всё хрень. В javascript всё объекты и всё может быть использовано как объект.
Вам просто нужно сделать свой класс с нужным протипом, и создавать объекты этого класса. |
Object.defineProperty(Object.prototype, 'isObject', { value: function () { return 'v' } }) var o = { a: 1 }; console.log(o.isObject()) var a = [1, 23] console.log(a.hasOwnProperty('isObject')) |
SuperZen, ты это к чему? "о" точно также не имеет "OwnProperty", а "a" точно также может сделать "isObject()".
|
Aetae, hasOwnProperty не смотрит на prototype, угу...
тогда выбор не большой, проверить что this имеет ф-ции из Array, но тогда может что-нибудь другое перестать работать... ) Object.defineProperty(Object.prototype, 'isObject', { value: function () { if (typeof this.find === 'function') { return 'array' } return 'object' } }) var o = { a: 1 }; console.log(o.isObject()) var a = [1, 23] console.log(a.isObject()) вообще кто-нибудь видел, знает есть ли они вообще такие люди, которые без справочника все это помнят и действительно знают как это все работает? видел тут на форуме кто-то писал, что он прочитал спецификацию ecmascript, одно дело прочитать, другое знать... это не риторический вопрос ), где они эти люди дайте хоть б... фотку посмотреть :) |
Цитата:
Если только Array - не object Но var a = function () {} var b = new RegExp ('d+') var c = new Number(123) console.log(a.isObject()) console.log(b.isObject()) console.log(c.isObject()) |
Часовой пояс GMT +3, время: 07:31. |