# lib/goog/reflect/reflect.js

1 | // Copyright 2009 The Closure Library Authors. All Rights Reserved.
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS-IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | /**
16 | * @fileoverview Useful compiler idioms.
17 | *
18 | * @author johnlenz@google.com (John Lenz)
19 | */
20 |
21 | goog.provide('goog.reflect');
22 |
23 |
24 | /**
25 | * Syntax for object literal casts.
26 | * @see http://go/jscompiler-renaming
27 | * @see http://code.google.com/p/closure-compiler/wiki/
28 | * ExperimentalTypeBasedPropertyRenaming
29 | *
30 | * Use this if you have an object literal whose keys need to have the same names
31 | * as the properties of some class even after they are renamed by the compiler.
32 | *
33 | * @param {!Function} type Type to cast to.
34 | * @param {Object} object Object literal to cast.
35 | * @return {Object} The object literal.
36 | */
37 | goog.reflect.object = function(type, object) {
38 | return object;
39 | };
40 |
41 |
42 | /**
43 | * To assert to the compiler that an operation is needed when it would
44 | * otherwise be stripped. For example:
45 | * <code>
46 | * // Force a layout
47 | * goog.reflect.sinkValue(dialog.offsetHeight);
48 | * </code>
49 | * @type {!Function}
50 | */
51 | goog.reflect.sinkValue = function(x) {
52 | goog.reflect.sinkValue[' '](x);
53 | return x;
54 | };
55 |
56 |
57 | /**
58 | * The compiler should optimize this function away iff no one ever uses
59 | * goog.reflect.sinkValue.
60 | */
61 | goog.reflect.sinkValue[' '] = goog.nullFunction;
62 |
63 |
64 | /**
65 | * Check if a property can be accessed without throwing an exception.
66 | * @param {Object} obj The owner of the property.
67 | * @param {string} prop The property name.
68 | * @return {boolean} Whether the property is accessible. Will also return true
69 | * if obj is null.
70 | */
71 | goog.reflect.canAccessProperty = function(obj, prop) {
72 | /** @preserveTry */
73 | try {
74 | goog.reflect.sinkValue(obj[prop]);
75 | return true;
76 | } catch (e) {}
77 | return false;
78 | };