具有自己的Collection Name的JS-prototype functionextension

时间:2018-02-10 12:13:08

标签: javascript prototype expand

我想用一些新功能扩展所有SVGElement。

例如:

SVGElement.prototype.logType= function () {
            console.log('I am a SVGelement from type: ' + this.nodeName);
        }

如果svgText是svgText-Objekt,我调用svgText.logType() 这很好用...... - > log是"我是SVGelement表单类型:svgText"

但我希望我的所有功能都带有前缀my。 我试过了:

SVGElement.my= {};
SVGElement.prototype.my.logType= function () {
    console.log('I am a SVGelement from type: ' + this.nodeName);
}

问题是,当我调用svgText.my.logType()时,"这个"指向"我的" -Objekt,而不是svgText-Object。

有办法吗?感谢帮助,对不起我的英语;)

1 个答案:

答案 0 :(得分:0)

如果你想在你所做的所有添加中加上“my”前缀,到目前为止最简单的方法是将它作为方法名称的一部分:

SVGElement.prototype.myLogType = function() { /*...*/ };
// ------------------^^

但一般来说,不要使用直接赋值来创建用作原型的对象的新方法,它会创建一个可枚举的属性,这往往会产生问题。相反,使用Object.defineProperty并且不要使新属性可枚举(默认情况下它将是不可枚举的。)

Object.defineProperty(SVGElement.prototype, "myLogType", {
    value: function() { /*...*/ },
    writable: true,
    configurable: true
});

但是,可能做你想做的事情,它只是(略微)低效和繁琐:使my具有访问者功能的属性并自定义生成你返回的对象第一次在实例上使用它。

见评论:

// Stand-in for SVGElement for the example
function FakeElement(id) {
  this.id = id;
}

// An object with the methods we want to add
var ourMethods = {
  logText: function() {
    return this.id;
  }
};

// Add our "my" property
Object.defineProperty(FakeElement.prototype, "my", {
  get() {
    // If we're being called on the prototype object itself, don't
    // do anything and just return null
    if (this === FakeElement.prototype) {
      return null;
    }
    
    // Define 'my' on this specific object with bound functions
    console.log("Creating 'my' for element id = " + this.id);
    var obj = this;
    var my = {};
    Object.keys(ourMethods).forEach(function(key) {
      my[key] = ourMethods[key].bind(obj);
    });
    Object.defineProperty(this, "my", {value: my});
    
    return my;
  }
});

// Test it
var f1 = new FakeElement(1);
var f2 = new FakeElement(2);
console.log(f1.my.logText());
console.log(f2.my.logText());
console.log(f1.my.logText());
console.log(f2.my.logText());

这是为了清晰起见,而不是简洁,如果我们利用ES2015 +对JavaScript的改进可能会更简洁,但希望它能让你开始......

相关问题