[英]JavaScript: prototype functions showing up in console
我只是注意到,當我記錄我正在處理的對象的實例時,我看到原型函數在它的屬性之后(它只有一個)。 這讓我覺得我做錯了什么。
這就是我設置原型的方式。
MF = function(x){
if(!(this instanceof MF)) return new MF(x);
this.node = x;
}
MF.prototype = {
show: function(display){
display ? this.node.style.display = display : this.node.style.display = 'block';
},
hide: function(){
this.node.style.display = 'none';
}
}
console.log(MF(window));
我也嘗試用Object.create()
設置它,正如在這個答案中所建議的那樣,在我的情況下沒有多大意義,但絕望的時候需要絕望的嘗試。
為什么我在實例中看到原型方法,我該如何解決這個問題?
例如,這里是jQuery
對象的樣子,日志中沒有顯示原型函數
您的代碼沒有出現任何問題。 我確定只有少數實例屬性才會將原型屬性列為方便。 擴展記錄的對象會顯示所有屬性都應該是它們應該存在的位置。
顯示原型對象是一種常規做法。 而使用jQuery,這也是轉載。 只需調用console.dir($('div'))
,您將在下面看到__proto__
對象。 您無法從控制台顯示中隱藏原型功能。
這就是我在我的庫中實現擴展原型的類的方法:
Pinch.$ = function(selector, parent) {
if (!(this instanceof arguments.callee)) {
var callee = arguments.callee,
newObject = Object.create(callee.prototype);
callee.apply(newObject, callee.arguments);
return newObject;
}
// --- logic ---
return this;
}
Pinch.prototype = Object.create({
is: function() {},
// --- methods ---
empty: function() {}
});
然后,如果您想用新方法擴展原型:
Pinch.$.prototype = Pinch.Util.extend(Pinch.$.prototype, {
newMethods: function() {}
}, {
oneMoreMethod: function() {}
});
您可以在許多庫中找到extend()
實現,只需使用Google搜索“擴展javascript”
它使用Object.create
作為擴展的第二種方式:
Pinch.$.prototype = Object.create(Pinch.$.prototype, {
newMethods: function() {}
});
但實際上,您無法從控制台隱藏原型對象。 只有當你開始使用基於本地范圍等的黑客和技巧時。
UPD:您可以使用Object.defineProperties()
隱藏元素 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties
例如:
var MF = function () {};
MF.prototype = Object.create({});
Object.defineProperties(MF.prototype, {
thisWillShow: {
value: function () {},
enumerable: true
},
thisWillNotShow: {
value: function () {},
enumerable: false
}
});
console.log(new MF());
這里的工作示例 - http://jsfiddle.net/uRVFW/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.