AngularJS $范围原型继承 - 原始与对象? [英] AngularJS $scope prototypal inheritance - primitive vs. objects?

查看:107
本文介绍了AngularJS $范围原型继承 - 原始与对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关于JavaScript的原型继承广泛阅读,特别是在孩子的作用域。我的理解是,我们始终确保一个。在我们的NG-模型绑定,以便它引用的对象。

I've read extensively about Javascript prototypal inheritance, specifically in child scopes. My understanding is that we always ensure a "." is in our ng-model binding so that it references an object.

我的问题是...为什么原型继承创建它的本地范围内的原始的,但不是一个对象?这似乎是同样的事情。

My question is ... why does prototypal inheritance create a primitive on its local scope but not an object? It seems like the very same thing.

在一个案例中,我们有一个原始的。在我们有一个对象,另一种情况 - 比如数组。什么是更令人困惑的是,我可以通过一个对象子范围(不带。),并通过将数据推到这是当地的范围内流传下来的对象,父对象还是被改变,因此没有子数组对象被创建。同样,为什么呢?原型继承似乎自动创建元......是什么让一个对象的不同?

In one case, we have a primitive. In another case we have an object - say an array. What's even more confusing is that I can pass an object to the child scope (without a ".") and by pushing data onto the object that was passed down within the local scope, the parent object is still modified and thus no child array object is created. Again, why? Prototypal inheritance seems to auto-create primitives ... what makes an object different?

推荐答案

下面是一个如何子范围从父范围内创建一个简化(为例子)版本。欲了解更多COM prehensive视图 - 转到的

Here's a simplified (for the example) version of how child scope is created from parent scope. For more comprehensive view - go to the source

父范围:

function Scope(){ }; 
var scope = new Scope(); // scope instance is created

假设它有一些原始的,有些对象属性:

Suppose it has some primitive and some object properties:

scope.a = 1;
scope.obj = {a: 1};

创建子作用域实例和它的原型是范围

Child scope instance is created and its prototype is "scope"

function ChildScope(){ };
ChildScope.prototype = scope;
var childScope = new ChildScope(); // an instance of the child scope

现在,让我们看到:

console.log(scope.a);          // should be 1
console.log(childScope.a);     // should be 1
console.log(scope.obj.a);      // should be 1
console.log(childScope.obj.a); // should be 1

正如预期的那样,对吧?

As expected, right?

如果我们现在在 childScope

childScope.a = 2;
childScope.obj.a = 3;

然后这里是输出:

Then here's the output:

console.log(scope.a);          // should still be 1
console.log(childScope.a);     // should be 2 now
console.log(scope.obj.a);      // should be 3
console.log(childScope.obj.a); // should be 3

的jsfiddle

所以,当你正在做的 NG-重复在原语的数组:在[A,B项,... ] ,并在其中使用<输入NG模型=项> ,你基本上是在做 childScope。项=...

So, when you are doing ng-repeat over array of primitives: item in ["a", "b",...] and within it use <input ng-model="item">, you are essentially doing childScope.item = "...".

这篇关于AngularJS $范围原型继承 - 原始与对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆