可重用的javascript对象,原型和范围

Max*_*Max 11 javascript scope prototype

MyGlobalObject;

function TheFunctionICanUseRightAwaySingleForAllInstansesAndWithoutInstanse() {
    function() {
        alert('NO CONSTRUCTOR WAS CALLED');
    }
};
Run Code Online (Sandbox Code Playgroud)

长命名函数必须可以调用MyGlobalObject,在window加载脚本后,它必须始终作为全局(to )变量可用.它应该支持符合最新标准的可扩展性.

我正处于如何为应用程序构建JS基础的架构困境(几乎100%JS).

我们需要一个对象即window.MyObject(像一个模块,比如jQuery)

它可以创建

VAR1

 var MyGlobalObjConstructor = function(){
     this.GlobalFunctionInObject = function(){
        alert('called with MyGlobalObj.GlobalFunctionInObject()');
        }        
};
window.MyGlobalObj = new MyGlobalObjConstructor();    
Run Code Online (Sandbox Code Playgroud)

MyGlobalObj可扩展的?我可以创建子对象,它将继承MyGlobalObj(MyGlobalObj.NewFunc例如扩展函数/属性)的当前状态吗?使用原型(VAR3)之间的主要区别是什么?

通过GlobaldFunction我的意思是所有的初始化/实例化(可能instantializable)情况下,单一实例..

或者

VAR2

var MyGlobalObj = {
    GlobalFunctionInObject: function...
    GlobalFunctionInObject2: function...
};
MyGlobalObj.GlobalFunctionInObject();
// here I lose all hierarchy elements, no prototype, 
// can I use GlobalFunctionInObject2 in GlobalFunctionInObject?
Run Code Online (Sandbox Code Playgroud)

或者

VAR3

var MyGlobalConstuctor = function(){} // already 'well-formed' object
MyGlobalConstuctor.prototype.GlobalFunctionInObject = function...
};
var MyGlobalObj = new MyGlobalConstuctor();

// so I'm sceptical to NEW, because I have ALREADY wrote my functions 
// which I expect to be in memory, single instance of each of them, 
// so creating MyObject2,3,4 with NEW MyGC() makes no sense to me.
// DO I REALLY HAVE TO USE "MyGlobalConstuctor.prototype." FOR EACH FUNCTION?!!!!
Run Code Online (Sandbox Code Playgroud)

定义MyGlobalObj为函数和对象(func或VAR2的结果)的区别是什么?

还是VAR4?

我在Chrome Debugger中看到了原型和__proto__特殊字段.我读过那没关系,但为什么他们没有保存在一个原型中呢?

那么,什么是实现正确的/最佳方式window.MyObject,让人们可以MyObject.MyFunction();有哪些变体1 2和3的差异(PRO /禁忌)?

A. *_*ada 31

变化1 - Mixin

function SomeType() {
    var priv = "I'm private";
    this.publ = "I'm public";
    this.action = function() {
        return priv + this.publ;
    };
}

var obj = new SomeType();
Run Code Online (Sandbox Code Playgroud)

使用此方法,每次调用时都会创建一个新对象new SomeType(),创建所有方法并将所有此方法添加到新对象.每次创建对象时.

优点

  • 它看起来像经典继承,因此很容易理解Java-C#-C++等人.
  • 它可以为每个实例设置私有变量,因为每个创建的对象都有一个函数闭包
  • 它允许多重继承,也称为Twitter-mixins或功能混合
  • obj instanceof SomeType 将返回真实

缺点

  • 它会消耗更多内存作为您创建的更多对象,因为每个对象都会创建一个新的闭包并再次创建它的每个方法.
  • 私有属性private不是protected,子类型无法访问它们
  • 没有简单的方法可以知道一个对象是否有一些Type作为超类.

遗产

function SubType() {
    SomeType.call(this);
    this.newMethod = function() {
        // can't access priv
        return this.publ;
    };
}

var child = new SubType();
Run Code Online (Sandbox Code Playgroud)

child instanceof SomeType 将返回false没有其他方法可以知道child是否具有SomeType方法,而不是查看它是否具有逐个方法.

变体2 - 具有原型设计的对象文字

var obj = {
    publ: "I'm public",
    _convention: "I'm public too, but please don't touch me!",
    someMethod: function() {
        return this.publ + this._convention;
    }
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将创建一个对象.如果您只需要这种类型的一个实例,那么它可能是最佳解决方案.

优点

  • 这很容易理解.
  • 高性能

缺点

  • 没有隐私,每个属性都是公共的.

遗产

您可以继承对象进行原型设计.

var child = Object.create(obj);
child.otherMethod = function() {
    return this._convention + this.publ;
};
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧浏览器,则需要保证Object.create工作:

if (!Object.create) {
    Object.create = function(obj) {
        function tmp() { }
        tmp.prototype = obj;
        return new tmp;
    };
}
Run Code Online (Sandbox Code Playgroud)

要知道对象是否是另一个对象的原型,您可以使用

obj.isPrototypeOf(child); // true
Run Code Online (Sandbox Code Playgroud)

变体3 - 构造函数模式

更新:这是ES6类的模式是糖语法.如果您使用的是ES6课程,那么您可以了解这种模式.

class SomeType {
    constructor() {
        // REALLY important to declare every non-function property here
        this.publ = "I'm public";
        this._convention = "I'm public too, but please don't touch me!";
    }
    someMethod() {
        return this.publ + this._convention;
    }
}

class SubType extends SomeType {
    constructor() {
        super(/* parent constructor parameters here */);
        this.otherValue = 'Hi';
    }
    otherMethod() {
        return this._convention + this.publ + this.otherValue;
    }
}
Run Code Online (Sandbox Code Playgroud)
function SomeType() {
    // REALLY important to declare every non-function property here
    this.publ = "I'm public";
    this._convention = "I'm public too, but please don't touch me!";
}

SomeType.prototype.someMethod = function() {
    return this.publ + this._convention;
};

var obj = new SomeType();
Run Code Online (Sandbox Code Playgroud)

如果您没有继承并且记得重新分配构造函数属性,则可以重新分配原型而不是添加每个方法:

SomeType.prototype = {
    constructor: SomeType,
    someMethod = function() {
        return this.publ + this._convention;
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您的页面中有下划线或jquery,请使用_.extend或$ .extend

_.extend(SomeType.prototype, {
    someMethod = function() {
        return this.publ + this._convention;
    }
};
Run Code Online (Sandbox Code Playgroud)

new引擎盖下的关键字简单地做到这一点:

function doNew(Constructor) {
    var instance = Object.create(Constructor.prototype);
    instance.constructor();
    return instance;
}

var obj = doNew(SomeType);
Run Code Online (Sandbox Code Playgroud)

你拥有的是一种功能,而不是没有方法; 它只有一个prototype带有函数列表的属性,new运算符意味着创建一个对象并使用此函数的prototype(Object.create)和constructor属性作为初始化器.

优点

  • 高性能
  • 原型链将允许您知道对象是否从某种类型继承

缺点

  • 两步继承

遗产

function SubType() {
    // Step 1, exactly as Variation 1
    // This inherits the non-function properties
    SomeType.call(this);
    this.otherValue = 'Hi';
}

// Step 2, this inherits the methods
SubType.prototype = Object.create(SomeType.prototype);
SubType.prototype.otherMethod = function() {
    return this._convention + this.publ + this.otherValue;
};

var child = new SubType();
Run Code Online (Sandbox Code Playgroud)

你可能认为它看起来像一套超级变种2 ......你会是对的.它就像变体2但具有初始化函数(构造函数);

child instanceof SubTypechild instanceof SomeType都将返回true

好奇心:引擎盖instanceof操作员确实是

function isInstanceOf(obj, Type) {
    return Type.prototype.isPrototypeOf(obj);
}
Run Code Online (Sandbox Code Playgroud)

变化4 - 覆盖 __proto__

当你Object.create(obj)在引擎盖下做它

function fakeCreate(obj) {
    var child = {};
    child.__proto__ = obj;
    return child;
}

var child = fakeCreate(obj);
Run Code Online (Sandbox Code Playgroud)

__proto__属性直接修改对象的隐藏[Prototype]属性.因为这可以打破JavaScript行为,所以它不是标准的.并且标准方式是首选(Object.create).

优点

  • 快速而高效

缺点

  • 非标
  • 危险的; 你不能有一个hashmap,因为__proto__key可以改变对象的原型

遗产

var child = { __proto__: obj };
obj.isPrototypeOf(child); // true
Run Code Online (Sandbox Code Playgroud)

评论问题

1. var1:SomeType.call(this)会发生什么?'呼叫'特殊功能?

哦,是的,函数是对象,使他们有方法,我会提到三:.CALL() ,.适用().bind()

在函数上使用.call()时,可以传递一个额外的参数,即上下文,this函数内部的值,例如:

var obj = {
    test: function(arg1, arg2) {
        console.log(this);
        console.log(arg1);
        console.log(arg2);
    }
};

// These two ways to invoke the function are equivalent

obj.test('hi', 'lol');

// If we call fn('hi', 'lol') it will receive "window" as "this" so we have to use call.
var fn = obj.test;
fn.call(obj, 'hi', 'lol');
Run Code Online (Sandbox Code Playgroud)

所以当我们这样做时,我们SomeType.call(this)将对象传递this给函数SomeCall,因为你记得这个函数会向object添加方法this.

2. var3:你的"真正定义属性"是指我在函数中使用它们吗?这是一个惯例吗?因为获取this.newProperty而不与其他成员函数在同一级别定义不是问题.

我的意思是你的对象所拥有的任何属性都不是必须在构造函数上定义的函数,而不是在原型上,否则你将面临一个更令人困惑的JS问题.你可以在这里看到它,但它不在这个问题的焦点之内.

3. Var3:如果我不重新分配构造函数会发生什么?

实际上你可能没有看到差异,这就是它成为一个危险的错误.每个函数的原型对象都有一个constructor属性,因此您可以从实例访问构造函数.

function A() { }

// When you create a function automatically, JS does this:
// A.prototype = { constructor: A };

A.prototype.someMethod = function() {
    console.log(this.constructor === A); // true
    this.constructor.staticMethod();
    return new this.constructor();  
};

A.staticMethod = function() { };
Run Code Online (Sandbox Code Playgroud)

这不是最佳实践,因为不是每个人都知道它,但有时它会有所帮助.但如果你重新分配原型......

A.prototype = {
    someMethod = function() {
        console.log(this.constructor === A); // false
        console.log(this.constructor === Object); // true
        this.constructor.staticMethod();
        return new this.constructor();  
    }
};
Run Code Online (Sandbox Code Playgroud)

A.prototype是一个新的对象,的实例Object比原型Object.prototypeObject.prototype.constructorObject.令人困惑,对吧?:P

因此,如果您覆盖原型并且不重置"构造函数"属性,它将引用Object而不是A,如果您尝试使用"构造函数"属性来访问某些静态方法,您可能会变得疯狂.


eos*_*erg 5

我通常决定返回一个具有属性的对象:

var newCat = function (name) {
return {name: name, purr: function () {alert(name + ' purrs')}};
};

var myCat = newCat('Felix');
myCat.name; // 'Felix'
myCat.purr(); // alert fires
Run Code Online (Sandbox Code Playgroud)

您可以通过调用newCat函数并扩展您获得的对象来继承:

var newLion = function (name) {
    var lion = newCat(name);
    lion.roar = function () {
        alert(name + ' roar loudly');
    }
    return lion;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一个全局猫对象:

var cats = (function () {

var newCat = function (name) {
    return {
        name: name,
        purr: function () {
            alert(name + ' is purring')
        }
    };
};

return {
    newCat: newCat
};
}());
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话:

var mySecondCat = cats.newCat('Alice');
Run Code Online (Sandbox Code Playgroud)