我不确定标题是否正确传达了我想要清楚说明的功能。但让我来阐述一下。
在 javascript 中,我们可以将变量实例化为空对象:
var person = {};
我们可以轻松地为其设置属性
person.name = "Bob"
但是,我们不能使用属性来分配对象:
person.pet.name = "Bob"
> Uncaught TypeError: Cannot set property 'name' of undefined
在 Angular 上你可以。例如这个朴素的代码。我有一个 Controller :
angular.module('someModule', [])
.controller('someController', [
Callback
]
function Callback(){
this.person = {}
}
然后 View 包含:
<input type="text" data-ng-model='vm.person.pet.name'>
其中 vm
是代表 Controller 的 View 模型。当我记录从输入中抓取的结果时,您会得到一个 person
对象,其中包含一个 pet
子对象,其属性为 name
什么给了?为什么 Angular 添加这个功能?(我假设是这个功能)严格来说是为了灵活性吗?
最佳答案
来自docs :
Forgiving
Expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general purpose language, the expression evaluations are primarily used for data binding, which often look like this:
{{a.b.c}}
It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}}
Similarly, invoking a function a.b.c() on undefined or null simply returns undefined.
简单来说就是html中的表达<input type="text" data-ng-model='vm.person.pet.name'>
不会随时间变化,但实际值为 vm.person.pet.name
做。
关于javascript - 为什么 Angular 允许动态对象创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38899043/