gpt4 book ai didi

javascript - 在javascript中实例化新对象时设置属性值

转载 作者:行者123 更新时间:2023-11-28 10:45:02 26 4
gpt4 key购买 nike

我想了解以下语法:(这是 Three.js 库)

var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

什么是 ( { color: 0x00ff00 } )

我知道:( { property: value } )

但是,我如何使用它?

我想创建一个函数来创建一个新的 div,但是,仅当属性为 null 时才创建。示例:

var dot = {

Viewport: function() {
this.container;

if (this.container == null) {
var newContainer = document.createElement("div");
newContainer.style.width = window.innerWidth + "px";
newContainer.style.height = window.innerHeight + "px";
newContainer.style.backgroundColor = "red"
document.body.appendChild(newContainer);
}
}
};

var oldDiv = document.getElementById("old");

var myViewport = new dot.Viewport({
container: oldDiv
});
<div id="old">old div</div>

如果我将 container 值设置为 oldDiv,如果我将 container 设置为 null,脚本不应创建新元素 它应该创建一个新元素。

最佳答案

这是一个 JavaScript 设计模式,名为 Mixin它的主要目的是用新的属性和值扩展对象,通常称为选项

它用于大多数 JavaScript 库,例如 Three.jsVue.jsjQuerydojo ...在定义模块时它很有帮助,它允许我们扩展或覆盖模块中的默认选项。

The Mixin Pattern可以看到那:

In JavaScript, we can look at inheriting from Mixins as a means of collecting functionality through extension. Each new object we define has a prototype from which it can inherit further properties. Prototypes can inherit from other object prototypes but, even more importantly, can define properties for any number of object instances. We can leverage this fact to promote function re-use.

Mixins allow objects to borrow (or inherit) functionality from them with a minimal amount of complexity. As the pattern works well with JavaScripts object prototypes, it gives us a fairly flexible way to share functionality from not just one Mixin, but effectively many through multiple inheritance.

即在以下示例中:

var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

我们正在为实例对象的 color 选项设置一个新值。

要进一步阅读,您可以查看dojo .mixin() , JavaScript Mixins: Beyond Simple Object ExtensionMixins, Forwarding, and Delegation文章。

<小时/>

but, How I use this?

解决方案:

根据您的情况,您可以使用 jQuery .extend()来实现它。

这就是您的代码:

var dot = {

Viewport: function(arguments) {

var defaults = {
container: null
};

this.settings = $.extend({}, defaults, arguments);

if (!this.settings.container) {
var newContainer = document.createElement("div");
newContainer.style.width = window.innerWidth + "px";
newContainer.style.height = window.innerHeight + "px";
newContainer.style.backgroundColor = "red"
document.body.appendChild(newContainer);
}
}
};

这将允许您使用以下语法来扩展默认选项并覆盖它:

var oldDiv = document.getElementById("old");

var myViewport = new dot.Viewport({
container: oldDiv
});

关于javascript - 在javascript中实例化新对象时设置属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com