其中是自定义函数中的属性
Where is the property in self-defining function?
我有一个关于自定义函数的问题。
var scareMe = function(){
console.log("Boo!");
var instance = this;
scareMe = function(){
console.log("Double Boo!");
return instance;
}
}
scareMe.prototype.nothing = true;
var un1 = new scareMe();
console.log(un1.nothing); //true
scareMe.prototype.everything = true;
var un2 = new scareMe();
console.log(un1 === un2); //true
它如我所料。
console.log(un2.everything); //undefined
在哪里可以获得"一切"属性?
它不起作用,因为一旦调用scareMe
,当您在初始调用后尝试更改原型时,您将用另一个函数覆盖scareMe
——实际上,您正在更改第二个方法的原型,而不是创建实例的第一个方法。因此,对原型的更改不会反映在您的实例中。
一种可能的解决方案是用第一个覆盖第二个对象的原型
var scareMe = function () {
console.log("Boo!");
var instance = this,
proto = scareMe.prototype;
scareMe = function () {
console.log("Double Boo!");
return instance;
}
scareMe.prototype = proto;
}
scareMe.prototype.nothing = true;
var un1 = new scareMe();
console.log('nothing', un1.nothing); //true
scareMe.prototype.everything = true;
var un2 = new scareMe();
console.log(un1 === un2); //true
console.log('everything', un1.everything); //true
演示:Fiddle
另一种写相同内容的方法可能是类似的东西
var scareMe = (function () {
var instance;
return function () {
if (instance) {
return instance;
}
instance = this;
}
})();
演示:Fiddle
相关文章:
- 自定义函数中的光标位置
- Google Sheet自定义函数返回0
- 其中是自定义函数中的属性
- 创建自定义函数以在函数上运行完整的多选下拉列表
- Google Sheets自定义函数条件格式
- dalek回调或自定义函数
- UI网格:如何从自定义函数访问MODEL_COL_FIELD
- 评估作为参数传递给 Google 电子表格中自定义函数的条件
- 具有自定义函数调用的 HTML 表单
- 使用 jQuery 对动态创建的元素调用自定义函数
- 从自定义函数返回promise
- 如何使用Angular 1.5组件将属性求值为字符串,这是一个自定义函数
- 如何重用jQuery中的自定义函数来应用多个css属性
- 使用HTMLElement作为自定义函数原型时的奇怪属性行为
- 从源自标签的onclick属性的自定义函数中调用preventdefault的访问事件
- 修改对象属性,然后在javascript自定义函数中调用函数
- 带有.data和html5 data属性的jQuery自定义函数
- 自定义函数中聚合物属性未定义
- Aurelia:访问Custom Element's的自定义函数或自定义属性
- JavaScript:路径的自定义函数's”;d”;属性