简体   繁体   English

从当前对象获取属性以在另一个对象中使用属性值

[英]Getting a property from current object to use the property value in another

Hello I'm looking on if its possible to get a property of an object and use it in another for example 您好,我正在研究是否有可能获取对象的属性并将其用于另一个对象

let obj = {
  something:"a string",
  name:"a test obj
  info: {
       name: need the name above
   }
}

So in the last nested name i want the Name above to be in there too, i tried like this.name but no luck 因此,在最后一个嵌套名称中,我也希望上面的名称也位于其中,我尝试使用this.name,但没有运气

As a different way to achieve your outcome you could use the getter function on your object. 作为获得结果的另一种方法,可以在对象上使用getter函数。

You basically create a method that will be run when you try to access a property on your object, you can intercept the call and return a different value, because it's at the root of your object it has the correct context to get the name property. 您基本上可以创建一个方法,当您尝试访问对象的属性时,该方法将运行,您可以拦截该调用并返回不同的值,因为它位于对象的根,它具有获取name属性的正确上下文。

 let obj = { something:"a string", name:"a test obj", get info() { return { name: this.name } } } console.log(obj.info.name) 

If you're going to reuse values like that just declare them as variables before creating the object: 如果要重用这样的值,只需在创建对象之前将它们声明为变量:

 const name = 'Bob'; const obj = { something: 'a string', name, info: { name } } console.log(obj); 

 var app = angular.module("app", []); app.controller("BaseController", function($scope) { let obj = {name:"a test obj"}; obj = {something:"a string",name:"a test obj", info: {name: obj.name} }; $scope.obj = obj; }); 
 <!DOCTYPE html> <html> <head> <script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app="app" ng-controller="BaseController"> {{obj}} </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM