문제

I'm trying to create a class constant, but I guess my novice-level understanding of JavaScript is showing. When this code executes:

var Class = function() {};
Class.prototype = { CONST : 1 };
var instance = new Class(),
c1 = instance.CONST,
c2 = Class.CONST;

the result is that c1 === 1 and c2 === undefined. Why isn't c2 === 1? Doesn't JavaScript look up the prototype chain for Class?

도움이 되었습니까?

해결책

what you trying to do is what would be called a class static method in other language.
To do that in Javascript you have to write

Class.CONST = 1; then you can call it with Class.CONST;

if you try to access it with instance method like new Class().CONST, it would be undefined

Back to your question, everything in Class.prototype is only accessible to an instance of the object(ie, created via new), not Class itself. Why?

Consider the implementation of new

Function.method('new', function () {
    var that = Object.create(this.prototype);
    var other = this.apply(that, arguments);
    return (typeof other === 'object' && other) || that;
});

first Object.create(this.prototype) create a brand new object which inherited from this.prototype which u declared via Class.prototype = { Const : 1 }, then it call this.apply(that, arguments), which just call your declared Class function using that as the this variable. then it return the object. You can see that the Class function is simply used as a way to stuff things into the newly born object create via new. and only the object created has access to the prototype methods.

다른 팁

You're trying to access the CONST property of a constructor (Class = function(){}). CONST won't be available until you instantiate Class.

A couple of good links about this:

The simple answer is that instances inherit from their constructor's public prototype, so c1 has a CONST property inherited from from Class.prototype (strictly, it's the instance's private [[Prototype]] property).

On the other hand, Class is an instance of Function, so it inherits from Function.prototype (i.e. its private [[Prototype]] is Function.prototype), not Class.prototype, so it doesn't have a CONST property.

The value of an object's [[Prototype]] is set when it's constructed and can never be changed. Replacing Class.prototype with some other object will only affect new instances.

Note that in some older Mozilla browsers (such as Firefox) there was a __proto__ property that referenced an object's [[Prototype]] and could be set, but that is now deprecated.

Generally it's best not to talk in terms of classes in regard to javascript, since it infers behaviour and features that can only be emulated to some extent.

Class is a function object. Function objects don't have a CONST property. It's used to construct a 'Class' object. 'Class' objects are custom objects which have a CONST property because it's declared in the constructor.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top