dojo 1.9: what annotation does declare.safeMixin add?

筅森魡賤 提交于 2019-12-13 16:27:53

问题


I have been reading through the dojo 1.9 documentation about declare.safeMixin(), focusing on the difference between it and lang.mixin.

Here is the explanation I found...

safeMixin() is a function defined in dojo/declare. It has the same functionality as dojo/_base/lang::mixin(), but additionally it annotates all copied methods compatibly with dojo/declare. This decoration can affect how this.inherited() works in mixed-in methods.

I can follow the example but it doesn't really explain exactly what is added and where, can anyone give any further examples of what annotation is added to each copied method?

So to be clear, I'm not asking for an explanation of inheritance, I'm just asking specifically about the annotations added by using declare.safeMixin() instead of lang.mixin.


回答1:


safeMixin adds the nom property to functions that are mixed in to the target. This property is set to the key from the source object that the function was assigned to. e.g. if you call declare.safeMixin(target, { foo: function() {} }), the nom property for that function is "foo". This is necessary for this.inherited(arguments) to automatically figure out that it should call the parent "foo". The alternative to using safeMixin would be to explicitly specify the name of the parent function: this.inherited('foo', arguments);.




回答2:


Using safeMixin allows you to mix functions into an instance that can take advantage of this.inherited the same way that prototype methods defined using declare can.

For example, the following will log 2 messages:

require([
    "dojo/_base/lang",
    "dojo/_base/declare"
], function(lang, declare){
    var A = declare(null, {
        method: function () {
            console.log('method in prototype');
        }
    });
    var a = new A();

    declare.safeMixin(a, {
        method: function () {
            this.inherited(arguments);
            console.log('method in instance');
        }
    });

    a.method();
});

Without safeMixin, you wouldn't be able to call this.inherited(arguments) from the overriding method (at least, not without additional parameters) - you'd end up getting an error:

Error: declare: can't deduce a name to call inherited()


来源:https://stackoverflow.com/questions/20123183/dojo-1-9-what-annotation-does-declare-safemixin-add

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!