[英]How Can I Access private method of other object (but it's same instanceof) in Javascript
var a1 = new A("test")
var a2 = new A("test2")
console.log(a2.getOtherValue(a1)) // -> expected "test"
a2.setOtherValue(a1, "test3") // set another object value
console.log(a1.getValue()) // -> expected "test3"
How Can I implement this?? 我该如何实施?
You can use getter and setter methods to create a property and on add, you can mutate own value. 您可以使用getter和setter方法创建属性,并在添加时更改自己的值。 Mutating other object using current object is a bad idea.
使用当前对象来突变其他对象是一个坏主意。
Following is a sample: 以下是一个示例:
function MyNumber(value) { var _value = value; Object.defineProperty(this, 'value', { get: function() { return _value; }, set: function(v) { if(!isNaN(v)) _value = v; } }); } MyNumber.prototype = (function() { var proto = {}; proto.add = function(o2) { if (o2 instanceof MyNumber) { this.value = this.value + o2.value; } else { throw new Error('Mismatched type. Expected an object of type MyNumber but got ' + o2.constructor.name); } } return proto; })(); var o1 = new MyNumber(10); var o2 = new MyNumber(20); o1.add(o2); console.log(o1.value); var o3 = { value: 40 } try { o1.add(o3); } catch (ex) { console.log(ex.message) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.